问题
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:
string.IsNullOrEmpty(e.NewValues[0].ToString())
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.
回答1:
Another way:
String.IsNullOrEmpty(Convert.ToString(e.NewValues[0]));
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.
回答2:
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:
string.IsNullOrEmpty(e.NewValues[0])
Update as of C# 6, you could also use:
string.IsNullOrEmpty(e.NewValues[0]?.ToString())
Or even:
$"{e.NewValues[0]}" == string.Empty
回答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()
{
}
}
回答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] )
回答5:
You'll need to check that e.NewValues[0] isn't null prior to doing a .ToString() on it.
回答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 ::
}
}
}
来源:https://stackoverflow.com/questions/18053126/how-to-convert-null-value-into-string-in-c-sharp-net