我正在使用gridview的默认更新方法,它允许我通过将单元格转换为文本框来更新gridview本身中的行。
我想检查验证,如果特定文本框(单元格)保持为空或空白,则不应更新其值。
为此,我写了以下代码:
string.IsNullOrEmpty(e.NewValues[0].ToString())
但是它给出了一个错误,比如没有将对象引用设置为对象的实例。可能无法将e.Newvalues[0]
的空值转换为字符串。
所有答案都提前得到赞赏。
答案 0 :(得分:3)
你可以这样做:
e.NewValues[0] == null || e.NewValues[0].ToString() == string.Empty
如果e.NewValues[0]
已经是字符串,您可以这样做:
string.IsNullOrEmpty(e.NewValues[0])
从C#6开始更新,你也可以使用:
string.IsNullOrEmpty(e.NewValues[0]?.ToString())
甚至:
$"{e.NewValues[0]}" == string.Empty
答案 1 :(得分:2)
另一种方式:
String.IsNullOrEmpty(Convert.ToString(e.NewValues[0]));
一些(可能是不需要的)解释:
Convert.ToString()
将为(string)null
返回null,并为(object)null
(或任何其他null)返回空字符串。
这两种情况都会给出预期结果,因为我们正在检查String.IsNullOrEmpty()
。
在任何情况下,它的行为都与someValue.ToString()
相同,除了它处理someValue
为空的情况。
答案 2 :(得分:1)
您可以使用这段代码
(e.NewValues[0] == null) ? string.Empty : e.NewValues[0].ToString()
如果不是null,上面的代码将返回等效的字符串,否则它将返回空字符串。
否则您可以使用以下代码。这将处理空案例。
string.IsNullOrEmpty(Convert.ToString( e.NewValues[0] )
答案 3 :(得分:1)
另一种(浪费)的方法是使用一个被覆盖的ToString
和??
的单身人士(过度杀戮但我可以使用??
:P)
(e.NewValues[0] ?? Empty._).ToString();
单身人士的代码在这里:
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 :(得分:0)
在对它执行.ToString()之前,您需要检查e.NewValues [0]是否为空。
答案 5 :(得分:0)
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 ::
}
}
}