Nathan McKaskle Nathan McKaskle - 23 days ago 13
C# Question

Check for null value in DataGrid View Field when Assigning Variable

I'm trying to assign a value to a string variable when making a change to a datagridview field. Unfortunately if it's blank, it crashes with a NullReferenceException even if I try to check if it's null. I also don't know of a more efficient way to write this.

string change = "";
if (dgGroups[cid, rid].Value.ToString() != null) //gets null reference exception if row/column is blank.
{
change = dgGroups[cid, rid].Value.ToString();
}

Answer

Your check should be like this. You are trying to call null.ToString() which is not valid and it will throw NullReferenceException .

string change = "";
if (dgGroups[cid, rid].Value != null)
{
    change = dgGroups[cid, rid].Value.ToString();
}

If you are using C# 6.0 you can write

string change = dgGroups[cid, rid].Value?.ToString();//this will return null if Value is null
Comments