Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a selected row in a datagridview is empty(has no item) C#

How would i go about checking if a row's cells have data in them, ie not empty/null.

I've been trying the following:

        if (dgvClient.SelectedRows.Count > 0)
        {
            DataGridViewRow currentRow = dgvClient.SelectedRows[0];
            if (currentRow.Cells.ToString() != String.Empty)
            {
                //The code that will be here will open a form
            }
            else
            {
                MessageBox.Show("Select a non null row");
            }
        }

However, it doesn't appear to be working, and I'm out of ideas :/

Thanks for any help, Ari

like image 239
Ari Avatar asked Nov 04 '11 08:11

Ari


People also ask

How check DataGridView row is empty C#?

You can find out if it is empty by checking the number of rows in the DataGridView. If myDataGridView. Rows. Count == 0 then your DataGridView is empty.

How do you fix rows Cannot be programmatically added to the DataGridView rows collection when the control is data bound?

Solution 1 Either you strip off the data binding and do the boilerplate code yourself. Or you add a new record to the datasource and refresh the gridview => it will update itself with the new row.


2 Answers

.Cells is a collection of DataGridViewCell objects.

You need to iterate through that collection & test each cell to see if it has a value...

if (currentRow.Cells.Count > 0) 
{      
   bool rowIsEmpty = true;    

   foreach(DataGridViewCell cell in currentRow.Cells)    
   {
      if(cell.Value != null) 
      { 
          rowIsEmpty = false;
          break;
      }    
   }

   if(rowIsEmpty)
   {
       MessageBox.Show("Select a non null row"); 
   }
   else
   {
       //DoStuff
   }
}
like image 58
Eoin Campbell Avatar answered Oct 13 '22 09:10

Eoin Campbell


Another method to check if a new empty row is selected perhaps

if(dataGridView.CurrentRow.Index == dataGridView.Rows.Count -1)
{
    //you selected a new row
}
like image 3
Jnr Avatar answered Oct 13 '22 09:10

Jnr