我从文本框中获取一个值并将其转换为十进制。但是,文本框值可能为空。那么,我如何处理文本框中的空字符串?
不幸的是,我有大约 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 个变量。我正在寻找一些在转换过程中处理空值而不添加额外代码行的代码。
最佳答案
But, the above code is displaying '0' in the textbox. User does not want to see '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())
关于c# - 当字符串为空时,用 '0' 替换字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24309234/