Reputation: 47
This is my code:
private void Bind()
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Dido\documents\visual studio 2012\Projects\CourseProjectCars\CourseProjectCars\DataCars.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from SuperCars", con);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
private void button4_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Dido\documents\visual studio 2012\Projects\CourseProjectCars\CourseProjectCars\DataCars.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand delcmd = new SqlCommand();
if (dataGridView1.Rows.Count > 1 && dataGridView1.SelectedRows[0].Index != dataGridView1.Rows.Count - 1)
{
delcmd.CommandText = "DELETE FROM SuperCars WHERE Car='%" + 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("Row Deleted");
}
Bind();
}
I want to put a delete button in my application. When I select a row and click the delete button, it throws the exception below:
Index was out of range. Must be non-negative and less than the size of the collection.
Upvotes: 0
Views: 761
Reputation: 63337
The problem is you don't know how to select a row as well as how the DataGridView
understands when a row is called selected. To select a row, you have to click on the row header, or if you want to select the row just by clicking on any cell on the row, just set the property SelectionMode
to DataGridViewSelectionMode.FullRowSelect
. Then the SelectedRows
should have at least 1 item, the index out of range exception should not be thrown any more.
If you intend to allow user to delete 1 row at a time, I think you can use the property CurrentRow
to get the current selected row, you can also use the CurrentCell
or CurrentCellAddress
and derive the selected row from them.
Upvotes: 1
Reputation: 2898
Please display the code in side Bind() function. I think record was not removed in the database and when you call Bind() function at that time record again bind in the gridview. I think your delete query is wrong , if you want to remove record which have car as cell[0] value so query will be as below :
delcmd.CommandText = "DELETE FROM SuperCars WHERE Car Like '%" +dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "%'";
Upvotes: 0