Click here to Skip to main content
15,900,511 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi All,

I am having a problem when I try to apply the method string.IsNullorEmpty() over an object, in my case, a dataGridView Cell.

My method verifies 2 cells of each line of a dataGridView and check if both Cells are filled if one of them is.

The problem is that when I use the code below...

C#
for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                if(!string.IsNullOrEmpty(dataGridView1.Rows[i].Cells["Column1"].Value.ToString()) && string.IsNullOrEmpty(dataGridView1.Rows[i].Cells["Column2"].Value.ToString()))
                {
                    MessageBox.Show("Please, enter a valid value for each description.");
                    return;
                }
                if(!string.IsNullOrEmpty(dataGridView1.Rows[i].Cells["Column2"].Value.ToString()) && string.IsNullOrEmpty(dataGridView1.Rows[i].Cells["Column1"].Value.ToString()))
                {
                    MessageBox.Show("Please, enter a valid description for each value.");
                    return;
                }
            }


I have the error Object reference not set to an instance of an object..

I know why it happens, but, I can't verify this cell using only
!string.IsNullOrEmpty(dataGridView1.Rows[i].Cells["Column2"].Value)<br />
... I have to use .ToString() after .Value, but, when I execute the code, it can't convert a null value to a string for it to use the method string.IsNullorEmpty().

How can I make it happens without have to error Object reference not set to an instance of an object.?

Thanks is advance! :)
Posted
Updated 2-Nov-10 0:49am
v2

1 solution

Because dataGridView1.Rows[i].Cells["Column2"].Value is of type Object, you can simply check for null:

C#
if(dataGridView1.Rows[i].Cells["Column2"].Value != null)
{
//your code here..
}


Once you know it's not null, you can go further and check if it's an empty string.
 
Share this answer
 
Comments
Hiren solanki 2-Nov-10 6:53am    
Accepted from myside.
lucasgrohl 2-Nov-10 7:10am    
Thanks! You helped a lot! =)

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