我想通过按下另一种形式的按钮从一个表单中的datagridview中删除记录。但我得到一个nullreferenceexception was unhandled
错误。我是c#的新手,所以如果有人能写我正确的代码,我会非常感激。通过在gridview上按钮单击选择来删除sql表中的记录
这是我到目前为止。
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@" Data Source=HOME-D2CADC8D4F\SQL;Initial Catalog=motociclete;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
DataGridViewRow dr = dataGridView1.Rows[i];
if (dr.Selected == true)
{
dataGridView1.Rows.RemoveAt(i);
try
{
con.Open();
cmd.CommandText = "Delete from motociclete where codm=" + i + "";
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
this.Close();
}
你在哪一行得到异常?我也注意到你在这里指的是多种形式。有关这方面的更多信息可能会对我们有所帮助。 –
我在这一行得到异常:for(int i = 0; i
stefan9976
当你得到一个异常时,你会得到一个行号,它告诉你它到底发生了什么。如果您在该行上设置断点,然后运行代码以找出导致异常的事件,这会很有帮助。如果您在问题中(而不是在评论中,而是在问题本身中)为我们确定了该行,则通过对该行进行评论或以其他方式标记该行,以便我们不必猜测,这也非常有帮助。毕竟,你知道*究竟是哪一行*,因为例外给你提供了这些信息。请与我们分享。 –