我想通過按下另一種形式的按鈕從一個表單中的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
當你得到一個異常時,你會得到一個行號,它告訴你它到底發生了什麼。如果您在該行上設置斷點,然後運行代碼以找出導致異常的事件,這會很有幫助。如果您在問題中(而不是在評論中,而是在問題本身中)爲我們確定了該行,則通過對該行進行評論或以其他方式標記該行,以便我們不必猜測,這也非常有幫助。畢竟,你知道*究竟是哪一行*,因爲例外給你提供了這些信息。請與我們分享。 –