Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# SQL DataGridView
I have a gridview that needs to edit update and delete from datagrid and from my sql server.
 
The problem is with my delete when i run my form and want to delete a row in my datagridview it gives an error index out of range.
 
Here is my form code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Configuration;
using System.Data.SqlClient;
using System.Windows.Forms.PropertyGridInternal;
 

namespace WindowsFormsApplication1
{
    public partial class Form5 : Form
    {
        SqlConnection con = new SqlConnection(@"Data Source=Admin-PC\SQLEXPRESS;Initial                             Catalog=Couriers;Integrated Security=True");
 
        public Form5()
        {
            InitializeComponent();
            FormBorderStyle = FormBorderStyle.None;
            WindowState = FormWindowState.Maximized;
            TopMost = true;
            Bind();
            
        }
 
        private void Clear()
        {
            textBox1.Text = string.Empty;
            comboBox1.Text = string.Empty;
            textBox7.Text = string.Empty;
            textBox6.Text = string.Empty;
            comboBox2.Text = string.Empty;
            textBox4.Text = string.Empty;
            textBox13.Text = string.Empty;
            textBox2.Text = string.Empty;
            textBox11.Text = string.Empty;
            textBox9.Text = string.Empty;
            textBox14.Text = string.Empty;
        }
        //save
        private void button6_Click(object sender, EventArgs e)
        {
            con.Open();
           SqlCommand cmd = new SqlCommand("Insert Into Waybills set (WaybillNumber,SenderName,SenderAdress,SenderContact,ReceiverName,ReceiverAdress,ReceiverContact,UnitDescription,UnitWeight,Price,Payee) Values (@WaybillNumber,@SenderName,@SenderAdress,@SenderContact,@ReceiverName,@ReceiverAdress,@ReceiverContact,@UnitDescription,@UnitWeight,@Price,@Payee)", con);
           cmd.Parameters.AddWithValue("@WaybillNumber", textBox1.Text);
           cmd.Parameters.AddWithValue("@SenderName", comboBox1.Text);
           cmd.Parameters.AddWithValue("@SenderAddress", textBox7.Text);
           cmd.Parameters.AddWithValue("@SenderContact", textBox7.Text);
           cmd.Parameters.AddWithValue("@ReceiverName", comboBox2.Text);
           cmd.Parameters.AddWithValue("@ReceiverAddress", textBox4.Text);
           cmd.Parameters.AddWithValue("@ReceiverContact", textBox13.Text);
           cmd.Parameters.AddWithValue("@UnitDescription", textBox2.Text);
           cmd.Parameters.AddWithValue("@UnitWeight", textBox11.Text);
           cmd.Parameters.AddWithValue("@Price", textBox9.Text);
           cmd.Parameters.AddWithValue("@Payee", textBox14.Text);
 
           cmd.ExecuteNonQuery();
           con.Close();
           MessageBox.Show("nEW DATA INSERTED");
           Bind();
           Clear();
           dataGridView1.Refresh();
       }
 

        private void Bind()
        {
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter("Select * from Waybills", con);
            DataTable dt = new DataTable();
            da.Fill(dt);
            dataGridView1.DataSource = dt;
            con.Close();
        }
 
       
 
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
 
        }
 
        private void Form5_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'couriersDataSet2.Waybills' table. You can move, or remove it, as needed.
            this.waybillsTableAdapter1.Fill(this.couriersDataSet2.Waybills);
            
 
        }
        //view data
        private void button1_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(@"Data Source=Admin-PC\SQLEXPRESS;Initial Catalog=Couriers;Integrated Security=True");
            con.Open();
       
            SqlDataAdapter ad = new SqlDataAdapter("select * from Waybills where WaybillNumber like '%" + textBox5.Text + "%'", con);
            SqlCommandBuilder cb = new SqlCommandBuilder(ad);
            DataSet ds = new DataSet();
            ds.Clear();
            ad.Fill(ds);
            dataGridView1.DataSource = ds.Tables[0];
            if (textBox5.Text == "" || ds.Tables[0].Rows.Count == 0)
            {
                dataGridView1.Visible = false;
            }
            else
            {
                dataGridView1.Visible = true;
                con.Close();
            }
            
        }
 
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
 
        }
 
        private void button2_Click(object sender, EventArgs e)
        {
            Form2 f2 = new Form2();
            f2.ShowDialog();
            this.Close();
        }
 
        private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
        {
 
        }
        //edit
        private void button3_Click(object sender, EventArgs e)
        {
            int i;
            i = dataGridView1.SelectedCells[0].RowIndex;
            textBox1.Text = dataGridView1.Rows[i].Cells[0].Value.ToString();
            comboBox1.Text = dataGridView1.Rows[i].Cells[1].Value.ToString();
            textBox7.Text = dataGridView1.Rows[i].Cells[2].Value.ToString();
            textBox6.Text = dataGridView1.Rows[i].Cells[3].Value.ToString();
            comboBox2.Text = dataGridView1.Rows[i].Cells[4].Value.ToString();
            textBox4.Text = dataGridView1.Rows[i].Cells[5].Value.ToString();
            textBox13.Text = dataGridView1.Rows[i].Cells[6].Value.ToString();
            textBox2.Text = dataGridView1.Rows[i].Cells[7].Value.ToString();
            textBox11.Text = dataGridView1.Rows[i].Cells[8].Value.ToString();
            textBox9.Text = dataGridView1.Rows[i].Cells[9].Value.ToString();
            textBox14.Text = dataGridView1.Rows[i].Cells[10].Value.ToString();
        }
        //delete rows
        private void button4_Click(object sender, EventArgs e)
        {
            SqlCommand delcmd = new SqlCommand();
            if (dataGridView1.Rows.Count > 1 && dataGridView1.SelectedRows[0].Index != dataGridView1.Rows.Count - 1)
            {
                delcmd.CommandText = " DELETE FROM Waybills WHERE WaybillNumber=" + dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "";
                con.Open();
                delcmd.Connection = con;
                delcmd.ExecuteNonQuery();
                con.Close();
                dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
                MessageBox.Show("Waybill Deleted");
            }
            Bind();
 
        }
        //update
        private void button5_Click(object sender, EventArgs e)
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("UPDATE Waybills set WaybillNumber = @WaybillNumber, SenderName = @SenderName, SenderAddress = @SenderAddress, SenderContact = @SenderContact, ReceiverName = @ReceiverName, ReceiverAddress = @ReceiverAddress, ReceiverContact = @ReceiverContact, UnitDescription = @UnitDescription, UnitWeight = @UnitWeight, Price = @Price, Payee = @Payee Where(WaybillNumber=@WaybillNumber)", con);
 
            cmd.Parameters.AddWithValue("@WaybillNumber", textBox1.Text);
            cmd.Parameters.AddWithValue("@SenderName", comboBox1.Text);
            cmd.Parameters.AddWithValue("@SenderAddress", textBox7.Text);
            cmd.Parameters.AddWithValue("@SenderContact", textBox7.Text);
            cmd.Parameters.AddWithValue("@ReceiverName", comboBox2.Text);
            cmd.Parameters.AddWithValue("@ReceiverAddress", textBox4.Text);
            cmd.Parameters.AddWithValue("@ReceiverContact", textBox13.Text);
            cmd.Parameters.AddWithValue("@UnitDescription", textBox2.Text);
            cmd.Parameters.AddWithValue("@UnitWeight", textBox11.Text);
            cmd.Parameters.AddWithValue("@Price", textBox9.Text);
            cmd.Parameters.AddWithValue("@Payee", textBox14.Text);
            
            cmd.ExecuteNonQuery();
            MessageBox.Show("updated");
            con.Close();
            Bind();
            Clear();
        }
 
    }
}
 
Can someone tell me where my problem is
Posted 6-Sep-12 21:18pm
Edited 6-Sep-12 21:27pm
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

Check selected row not eqal to -1
private void button4_Click(object sender, EventArgs e)
       {
if(dataGridView1.SelectedRows[0].Index != -1)
 {
           SqlCommand delcmd = new SqlCommand();
           if (dataGridView1.Rows.Count > 1 && dataGridView1.SelectedRows[0].Index != dataGridView1.Rows.Count - 1)
           {
               delcmd.CommandText = " DELETE FROM Waybills WHERE WaybillNumber=" + dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "";
               con.Open();
               delcmd.Connection = con;
               delcmd.ExecuteNonQuery();
               con.Close();
               dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
               MessageBox.Show("Waybill Deleted");
           }
           Bind();
    }
 
 }
  Permalink  
Comments
GoggatjieLiesl at 11-Sep-12 7:28am
   
Thanks its working
pradiprenushe at 11-Sep-12 7:45am
   
Welcome
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

The problem is in this line..
if (dataGridView1.Rows.Count > 1 && dataGridView1.SelectedRows[0].Index != dataGridView1.Rows.Count - 1)
try with..
if (dataGridView1.Rows.Count >= 1 && dataGridView1.SelectedRows[0].Index == dataGridView1.Rows.Count - 1)
  Permalink  
Comments
GoggatjieLiesl at 7-Sep-12 2:36am
   
Thank you very much for the quick answer back
GoggatjieLiesl at 11-Sep-12 5:41am
   
Hey i tried changing my code to if (dataGridView1.Rows.Count >= 1 && dataGridView1.SelectedRows[0].Index == dataGridView1.Rows.Count - 1) now the program just keeps on running when i press delete button, it doesnt even want to exit application. please help
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

Hey i tried changing my code to if (dataGridView1.Rows.Count >= 1 && dataGridView1.SelectedRows[0].Index == dataGridView1.Rows.Count - 1) now the program just keeps on running when i press delete button, it doesnt even want to exit application. please help
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 290
1 Jochen Arndt 150
2 Kornfeld Eliyahu Peter 149
3 PIEBALDconsult 110
4 Richard MacCutchan 105
0 OriginalGriff 6,080
1 DamithSL 4,648
2 Maciej Los 4,087
3 Kornfeld Eliyahu Peter 3,624
4 Sergey Alexandrovich Kryukov 3,294


Advertise | Privacy | Mobile
Web03 | 2.8.141220.1 | Last Updated 11 Sep 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100