Click here to Skip to main content
15,886,806 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello

I am getting a nullReferenceException when accessing cells in datagridview.
I've tried these to check for the empty cell (so to not access it), none of them is working for me. Any help??
C#
if (dataGridView2.Rows[0].Cells[col].Value!=DBNull.Value)

if (string.IsNullOrEmpty(dataGridView2.Rows[0].Cells[col].Value.ToString()) == false)

String s=dataGridView2.Rows[0].Cells[col].Value.ToString();
if(IsNullOrEmpty(s))
Posted
Updated 29-Aug-13 4:06am
v3
Comments
GuyThiebaut 29-Aug-13 10:06am    
Try this:

if (dataGridView2.Rows[0].Cells[col]!=DBNull)

1 solution

How about this:
C#
if (dataGridView2.Columns[e.ColumnIndex].Name == "ColumnName")
        {
            if (String.IsNullOrEmpty(e.FormattedValue.ToString()))
            {
                dataGridView1.Rows[e.RowIndex].ErrorText =
                    "Column Name must not be empty";
                e.Cancel = true;
            }
        }

Also can use:
C#
foreach (DataGridViewRow rw in this.dataGridView2.Rows)
{
  for (int i = 0; i < rw.Cells.Count; i++)
  {
    if (rw.Cells[i].Value == null || rw.Cells[i].Value == DBNull.Value || String.IsNullOrWhitespace(rw.Cells[i].Value.ToString())
    {
      // Do your stuff...
    }
  }
}
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900