我从文本框中取值并将其转换为小数。但是,文本框值可能为空。那么,我怎样才能处理文本框中的空字符串?
不幸的是我有大约50个文本框要处理,所以像'检查带有IF条件的空'这样的答案对我没有帮助。如果我使用所有这些IF条件,我的代码看起来很难看。
我有这个
Convert.ToDecimal(txtSample.Text)
为了处理空值,我做了这个
Convert.ToDecimal(txtSample.Text = string.IsNullOrEmpty(txtSample.Text) ? "0" : txtSample.Text)
但是,上面的代码在文本框中显示“0”。用户不希望看到“0”。另一个解决方案是将文本框值转换为变量并转换变量,如下所示。
string variable = txtSample.Text;
Convert.ToDecimal(variable = string.IsNullOrEmpty(variable) ? "0" : variable)
但同样,我不想定义大约50个变量。我正在寻找一些在转换过程中处理空值而不添加额外代码行的代码。
答案 0 :(得分:10)
但是,上面的代码显示的是' 0'在文本框中。用户不希望看到' 0'。
这是因为您的语句将新值分配给txtSample.Text
(当您执行txtSample.Text = ...
时)。只需删除作业:
Convert.ToDecimal(string.IsNullOrEmpty(txtSample.Text) ? "0" : txtSample.Text)
如果要处理许多文本字段,为了方便起见,您可以定义扩展方法:
public static string ZeroIfEmpty(this string s)
{
return string.IsNullOrEmpty(s) ? "0" : s;
}
并像这样使用它:
Convert.ToDecimal(txtSample.Text.ZeroIfEmpty())
答案 1 :(得分:1)
您可以创建一个函数来防止在整个地方复制代码。
decimal GetTextboxValue(string textboxText)
{
return Convert.ToDecimal(string.IsNullOrEmpty(textboxText) ? "0" : textboxText);
}
然后像这样使用它:
GetTextboxValue(txtSample.Text);
答案 2 :(得分:0)
您可以为字符串创建扩展方法,如下所示
public static decimal ToDecimal(this string strValue)
{
decimal d;
if (decimal.TryParse(strValue, out d))
return d;
return 0;
}
然后你可以在每个地方只有txtSample.Text.ToDecimal()。