我想通过按另一种形式的按钮从一种形式的datagridview中删除一条记录。但我收到一个nullreferenceexception was unhandled
错误。我是 c# 的新手,所以如果有人能给我写正确的代码,我将不胜感激。
这是我到目前为止所得到的。
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();
}