How to convert null value into string in c# .net?

I am using gridview’s default update method in which it allows me to update row in gridview itself by converting cells into textboxes.

I want to check validations that if a particular textbox (cell) remains empty or blank then it should not update its value.

For that i have written following code:


But it gives an error like object reference not set to an instance of an object. May be it can not convert null value of e.Newvalues[0] to string.

All answers are appreciated in advance.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

You could do this:

e.NewValues[0] == null || e.NewValues[0].ToString() == string.Empty

If e.NewValues[0] is already a string, you could just do this:


Update as of C# 6, you could also use:


Or even:

$"{e.NewValues[0]}" == string.Empty

Solution 2

Another way:


A bit of (probably unneeded) explanation:

Convert.ToString() will return null for a (string)null, and an empty string for an (object)null (or any other null).

Either case will give the expected result, because we’re checking with String.IsNullOrEmpty().

In any case, its behaviour is the same as someValue.ToString() except it handles the cases where someValue is null.

Solution 3

Another (wasteful) way to do it is with a singleton with an overridden ToString and ?? (overkill but it lets me use ?? :P)

(e.NewValues[0] ?? Empty._).ToString();

The code for the singleton is here:

public sealed class Empty
    private static readonly Lazy<Empty> lazy =
        new Lazy<Empty>(() => new Empty());
    public override string ToString()
        return "";
    public static object _ { get { return lazy.Value; } }
    private Empty()

Solution 4

You can use this piece of code

 (e.NewValues[0] == null) ? string.Empty : e.NewValues[0].ToString()

The above code will will return the string equivalent if not null, otherwise it will return empty string.

Otherwise you can use following code. This will handle the null case.

string.IsNullOrEmpty(Convert.ToString( e.NewValues[0] )

Solution 5

You’ll need to check that e.NewValues[0] isn’t null prior to doing a .ToString() on it.

Solution 6

protected void grd_RowUpdating(object sender, GridViewUpdateEventArgs e)
     GridViewRow row = grd.Rows[e.RowIndex];
     for (int i = 0; i <= row.Cells.Count; i++)
         String str = ((TextBox)(row.Cells[i].Controls[0])).Text;
         if (!string.IsNullOrEmpty(str))
          //Your Code goes here ::

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply