Click here to Skip to main content
15,893,594 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am wondering if there is a more eloquent way to express the code below? I can't seem to get the IsNullOrEmpty method to work with data inside of a DataGridView so whenever a cell is null an exception is thrown.

This works, but it seems to be a bit of a work around (maybe not) and I have the same issue when checking the value of a checkbox in the grid which caused me to write more code for that work around.

Any suggestions are greatly appreciated.

C#
private bool IsRowValid( DataGridViewRow row )
{
    bool retVal = false;
    try
    {
        if( ( string.IsNullOrEmpty( row.Cells[ "Quantity" ].Value.ToString() ) != true ) &&
            ( string.IsNullOrEmpty( row.Cells[ "Unit" ].Value.ToString() ) != true ) &&
            ( string.IsNullOrEmpty( row.Cells[ "Cell" ].Value.ToString() ) != true ) &&
            ( string.IsNullOrEmpty( row.Cells[ "Station" ].Value.ToString() ) != true ) )
        {
            retVal = true;
        }
    }
    catch( NullReferenceException )
    {
        retVal = false;
    }
    return retVal;
}
Posted

The problem in that code is that row.Cells[ "Quantity" ].Value can be null, but you call ToString on that without checking for that.

Change:

C#
string.IsNullOrEmpty( row.Cells[ "Quantity" ].Value.ToString() )


to

C#
string.IsNullOrEmpty( row.Cells[ "Quantity" ].Value as String)


Btw please don't do != true, that's ugly to see and not recommended practice. Instead do this:

C#
if( !String.IsNullOrEmpty(...))...
 
Share this answer
 
v3
Comments
Jeff Patterson 5-Nov-10 10:27am    
Thank you!
Your sample explains to me why my initial check for null (not shown) didn't work. This is far better.

I agree that !=true is ugly. I will implement both of your suggestions. Again thank you.
Nish Nishant 5-Nov-10 10:29am    
Np, you are welcome.
I don't know of a more elegant way, although somebody probably will.

The only thing I would say is that it could be very slightly shorter

C#
if ( ( !string.IsNullOrEmpty( row.Cells[ "Quantity"].Value.ToString() )) &&
   ( !string.IsNullOrEmpty( row.Cells[ "Unit"].Value.ToString() )) &&
   ( !string.IsNullOrEmpty( row.Cells[ "Cell"].Value.ToString() )) &&
   ( !string.IsNullOrEmpty( row.Cells[ "Station"].Value.ToString() )) )


possibly at the expense of readability.
 
Share this answer
 
Comments
Jeff Patterson 5-Nov-10 10:29am    
You are right and with Nishant's null suggestion I have something that works better reads clearer.

Thank you

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