none
Check if the data in datagridview is empty or null RRS feed

  • Question

  • Hai, i want to ask a question. How do i check that if the selected row is empty (contains nothing) in DataGridView and if the user select empty row in DataGridView, and click delete, the message will come out like this "Could not be deleted, because this is an empty row"? How do i do that?

    I already tried this code, but it is gave me the error: 
    Object reference not set to an instance of an object. NullReferenceException
    And the error pointed at: (in the Delete function)

    int rowNum = dataGridView1.CurrentRow.Index;

    Here is the code:
    private void DeleteDatabase(object sender, EventArgs e)
            {
                if (dataGridView1.SelectedRows.Count != 0)
                {
                    if (choice.comboBox1.Text == "English")
                    {
                        System.Media.SoundPlayer sound = new System.Media.SoundPlayer(@"C:\Windows\Media\Windows Exclamation.wav");
                        sound.Play();
                        MessageBox.Show("You Have Not Selected Any Rows!", "Error");
                    }
                }
    
                else
                {
                    Delete(sender, e);
                }
            }

    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("Could not be deleted. There is no Data in this Row!", "Error");
                            }
    
                            else
                            {
                                Delete(sender, e);
                            }
                        }
                    }
                 }


    Saturday, September 14, 2013 4:47 PM

Answers

  • I'm an idiot, sorry Fuhans ... I should  have said to check the dt.DefaultView.Count instead of dt.Rows.Count. In fact, I started to post it that way, but got distracted in the middle of my post and when I came back to it, I forgot to change it to dt.DefaultView.Count.  Very sorry!!!!

    And also, sorry for the slow reply ... I did not get a notification email when you replied almost 6 hours ago.


    ~~Bonnie Berent DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Sunday, September 15, 2013 10:55 PM

All replies

  • Hi Fuhans, we meet again! ;0)

    Since you've already deleted the row in the DataTable, you don't need to delete it from the DataGridView. This is because the grid's DataSource is the DataTable. Once it's deleted from the DataTable, it's also gone from the grid. You've changed my code a little bit (that I posted for you in a different thread) ... you'll notice that in that code all I deleted was the row from the DataTable (it's actually deleted from the DataTable.DefaultView ... which amounts to the same thing, and does need to be done that way in order to correspond correctly to the grid's CurrentRow.Index).

    Does this help explain it better?


    ~~Bonnie Berent DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Saturday, September 14, 2013 8:51 PM
  • Hai Ms BonnieB, pleasure to meet you again! :D

    by the way, i knew that (i don't need to delete it from the datagridview, since i already deleted it from the DataTable, since this below code is already told me that the datagridview is connected to the DataTable, so when the DataTable is deleted, does the datagridview. Correct me if i am wrong miss.

    DataTable dt = (DataTable)dataGridView1.DataSource; // Tell system that datagridview data source is same with DataTable

    int rowNum = dataGridView1.CurrentRow.Index; // Look up if the current selected row has data or not
    int id = Convert.ToInt32(dt.DefaultView[rowNum]["ID"]); // Get the variable that hold variable selected number rows and tell the system that the selected number rows is based on ID (in the database).
    dt.DefaultView[rowNum].Delete(); // When it does has data (ID), it will execute the delete parameters, function.

    What i confuse and now trying to solve is, when the DataTable or datagridview is blank (nothing inside it / there is no data in there), like below picture:

    and when i click the "Delete" button and when i select the first row (which is blank, shown like the picture above), it will say something like this: Cannot be deleted, because this row is an empty row!.

    When i run the program, and click the "Delete" button, it suppose show the message: Cannot be deleted, because this row is an empty row!. But it is not, however it gave me the error: 

    Object reference not set to an instance of an object. NullReferenceException

    Basically, what i want is like this: 

    what happens if the user clicking the "Delete" button when there is no data in that selected row (All the rows all empty and yet the user still clicking the "Delete" button? (Like shown in the picture above) 

    Sunday, September 15, 2013 5:41 AM
  • That row depicted in your picture does not yet exist ... as you probably know, it's how the grid shows the user where they can add a new row. In your Delete button click handler, check the DataTable's Rows.Count to be sure you actually have rows:

    DataTable dt = (DataTable)dataGridView1.DataSource; // Tell system that datagridview data source is same with DataTable
    
    if (dt.Rows.Count > 0)
    {
        int rowNum = dataGridView1.CurrentRow.Index; // Look up if the current selected row has data or not
        int id = Convert.ToInt32(dt.DefaultView[rowNum]["ID"]); // Get the variable that hold variable selected number rows and tell the system that the selected number rows is based on ID (in the database).
        dt.DefaultView[rowNum].Delete(); // When it does has data (ID), it will execute the delete parameters, function.
    }


    ~~Bonnie Berent DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Sunday, September 15, 2013 3:26 PM
  • Hai Miss, thanks it is worked. But only for the first time when the user not entering any data. The code is like this, i let user view the Database through datagridview in the program when user run the program.

    if (dt.Rows.Count > 0)
                {
                    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();
                        }
    
                        conn.Close();
                    }
                }
    
                else if (dt.Rows.Count <= 0)
                {
                    if (choice.comboBox1.Text == "English")
                    {
                        System.Media.SoundPlayer sounds = new System.Media.SoundPlayer(@"C:\Windows\Media\Windows Exclamation.wav");
                        sounds.Play();
                        MessageBox.Show("There is no Data in the Selected Row!", "Error");
                        return;
                    }
                }

    When the user entering data, and delete it. The data deleted successfully, but when the user click "delete" button again after the user deleted data, it is gave same error.

    This is the screenshot (i mixed 3 screenshots into 1 image):

    ----Description of Screenshot 1 (Left Image)-----:

    when i run the program at 12:38 AM, and when i click "delete" button, it gave like the screenshot (1) above (Note: it is correct).

    -----Description of Screenshot 2 (Middle Image)-----:

    the program still active at 12:39 AM, and everything still fine (the data has been added, and the "delete" function runs, because there is a data in the selected row).

    ----Description of Screenshot 3 (Right Image)-----:

    the program still active at 12:40 AM, the previous data (see screenshot 2) has been deleted, and the selected rows empty again and when i click the "delete" button, the message box didn't show like the screenshot 1, however it gave the same error. (This is the problem that i am facing)


    Note: Sorry for the small images size.
    Sunday, September 15, 2013 4:59 PM
  • I'm an idiot, sorry Fuhans ... I should  have said to check the dt.DefaultView.Count instead of dt.Rows.Count. In fact, I started to post it that way, but got distracted in the middle of my post and when I came back to it, I forgot to change it to dt.DefaultView.Count.  Very sorry!!!!

    And also, sorry for the slow reply ... I did not get a notification email when you replied almost 6 hours ago.


    ~~Bonnie Berent DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Sunday, September 15, 2013 10:55 PM
  • Nah, it's okay miss, i also didn't get the notification in my email about this forum, so i bookmark it.. haha..

    No No No! You're totally wrong, you're not an idiot miss, however i am an idiot and you're a genius!. I always ask and ask (whenever got an error, always ask without try harder first) this kind of stuffs to my own project (program). I am so sorry. 

    Okay, i understand now miss why i have to use dt.DefaultView.Count , despite have to use dt.Rows.Count. Thank you very much!

    Sincerely,

    Fuhans

    Monday, September 16, 2013 5:18 AM
  • You're welcome, Fuhans! I'm glad I could help! Even though I'm not a genius (but thank you for the kind words).  =0)

    ~~Bonnie Berent DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Monday, September 16, 2013 4:00 PM