Check if the data in datagridview is empty or null
I have a problem, probably you guys in this forum could help me.
Here is my problem:
I want to show the MessageBox that say there is no data in datagridview,
you cannot delete it. I already can delete the data in the datagridview,
but when the datagridview contains 0 data, and i click delete "button", it
is error. The error is: Object reference not set to an instance of an
object. NullReferenceException
Here is the code that pointed by the error: int rowNum =
dataGridView1.CurrentRow.Index;
Here is the code:
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);
}
}
}
}
Does anyone knows how to fix it?
No comments:
Post a Comment