[英]How to delete a selected row from datagridview?
if (dgvProductCatalog.Rows.Count > 1 && dgvProductCatalog.SelectedRows[0].Index != dgvProductCatalog.Rows.Count - 1)
{
cmd = new SqlCommand("DELETE FROM Products WHERE ProductId= " + dgvProductCatalog.SelectedRows[0].Cells[0].Value.ToString() + " " , connection);
try
{
connection.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
connection.Close();
dgvProductCatalog.Rows.RemoveAt(dgvProductCatalog.SelectedRows[0].Index);
MessageBox.Show("Record Deleted Successfully!");
DisplayData();
ClearData();
}
}
I am using the above piece of code on a button click to delete a selected row but i am getting " System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. " What am I doing wrong here? 我在按钮单击上使用上面的代码以删除选定的行,但我收到“ System.ArgumentOutOfRangeException:索引超出范围。必须为非负数,并且小于集合的大小。 ”这里做错了吗?
Thanks! 谢谢!
I would use currentRow instead 我会改用currentRow
dgvProductCatalog.CurrentRow.Cells[0].Value
Then 然后
dgvProductCatalog.Rows.RemoveAt(dgvProductCatalog.CurrentRow.Index)
or 要么
dgvProductCatalog.Rows.RemoveAt(dgvProductCatalog.SelectedCells[0].RowIndex)
Also while you are at it, I would change this line too 另外,当您在使用时,我也会更改此行
if (dgvProductCatalog.Rows.Count > 1 && dgvProductCatalog.SelectedCells.count > 0)
My guess is the if statement above is running when the selectedCells.Count = -1 我的猜测是,当selectedCells.Count = -1时,上述if语句正在运行
Lastly, as just a suggestion, instead of 最后,作为建议,而不是
WHERE ProductId= " + Cell.Value + " "
I would use 我会用
WHERE ProductId='" + Cell.Value + "'"
The ' is important for mitigating possible errors. '对于减轻可能的错误很重要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.