Reputation: 99
I know this topic is a frequently asked question,but i can't figure out the problem here.
The problem is my remove button is removing the row below the selected row.And as an extended problem there is an error while trying to delete the last row.
I think the issue is in dataGridView2.Rows[i].Cells[0].Value
This supposed to take the Id value from the grid and delete the according record but it's not working properly. Thanks in advance for the help.
private void removeButton1_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection("Data Source=TEST;Initial Catalog=TEST;Persist Security Info=True;User ID=123;Password=123"))
{
SqlCommand cmd = new SqlCommand();
conn.Open();
for (int i = dataGridView2.Rows.Count - 1; i >= 0; i-- )
{
DataGridViewRow delrow = dataGridView2.Rows[i];
if (delrow.Selected == true)
{
dataGridView2.Rows.RemoveAt(i);
try
{
cmd.CommandText = "DELETE FROM dbo.deneme_log WHERE id=" + dataGridView2.Rows[i].Cells[0].Value + "";
cmd.Connection = conn;
int count = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
conn.Close();
}
}
Upvotes: 0
Views: 105
Reputation: 1898
First, you delete row i
from the grid and then you are trying to delete it from the database, but you access it by the same index i
which points now to the next row. As an easy fix you need to use delrow
variable for construction cmd.CommandText
value. And also there is the SelectedRows
property in the GridView
so you don't need to walk throw all rows.
Upvotes: 2