我有一个问题,也许这个论坛的你们可以帮助我。
这是我的问题:
我想显示 MessageBox 说 datagridview 中没有数据,你不能删除它。我已经可以删除datagridview中的数据,但是当datagridview包含0数据时,我点击删除“按钮”,这是错误的。错误是:Object reference not set to an instance of an object. NullReferenceException
这是错误指向的代码:
int rowNum = dataGridView1.CurrentRow.Index;
这是代码:
private void Delete(object sender, EventArgs e)
{
DataTable dt = (DataTable) dataGridView1.DataSource;
int rowNum = dataGridView1.CurrentRow.Index;
int id = Convert.ToInt32(dt.DefaultView[rowNum]["ID"]);
dt.DefaultView[rowNum].Delete();
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string query = "DELETE FROM [Table] WHERE [ID] = @ID";
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("@ID", id);
cmd.ExecuteNonQuery();
}
if (choice.comboBox1.Text == "English")
{
System.Media.SoundPlayer sound = new System.Media.SoundPlayer(@"C:\Windows\Media\Windows Exclamation.wav");
sound.Play();
MessageBox.Show("Deleted Successfully!", "Deleted");
if (rowNum == 0)
{
bool rowIsEmpty = true;
foreach (DataGridViewCell cell in dataGridView1.CurrentRow.Cells)
{
if (cell.Value != null)
{
rowIsEmpty = false;
break;
}
}
if (rowIsEmpty)
{
System.Media.SoundPlayer sounds = new System.Media.SoundPlayer(@"C:\Windows\Media\Windows Exclamation.wav");
sounds.Play();
MessageBox.Show("Tidak ada Data di Baris ini!", "Error");
}
else
{
Delete(sender, e);
}
}
}
}
}
有谁知道如何解决它?