问题描述
我要从文本框中获取一个值并将其转换为十进制。但是,文本框值可以为空。因此,我该如何处理文本框中的空字符串?
I'm taking a value from a textbox and converting it to decimal. But, the textbox value could be empty. So, how could I handle empty strings from the textbox?
不幸的是,我有大约50个文本框要处理,因此诸如在IF条件下检查null这样的答案就可以了。帮帮我。如果我使用所有这些IF条件,我的代码将很难看。
Unfortunately I have around 50 textboxes to deal with, so answers like 'check for null with IF condition' won't help me. My code will look ugly if I use all those IF conditions.
我有这个
Convert.ToDecimal(txtSample.Text)
要处理空值,我这样做了
To handle nulls, I did this
Convert.ToDecimal(txtSample.Text = string.IsNullOrEmpty(txtSample.Text) ? "0" : txtSample.Text)
但是,上面的代码在文本框中显示为 0。用户不想看到 0。另一个解决方案是将文本框值转换为变量,然后将变量转换如下。
But, the above code is displaying '0' in the textbox. User does not want to see '0'. Another solution is to take text box value into a variable and convert the variable like below.
string variable = txtSample.Text;
Convert.ToDecimal(variable = string.IsNullOrEmpty(variable) ? "0" : variable)
But again, I do not want to define around 50 variables. I am looking for some piece of code that handles null values during conversion without adding the extra line of code.
推荐答案
这是因为您的语句将新值分配给 txtSample.Text
(当您执行 txtSample.Text = ...
时)。只需删除分配:
This is because your statement is assigning the new value to txtSample.Text
(when you do txtSample.Text = ...
). Just remove the assignment:
Convert.ToDecimal(string.IsNullOrEmpty(txtSample.Text) ? "0" : txtSample.Text)
如果要处理的文本字段很多,可以使事情变得简单,可以定义扩展方法:
To make things easier if you have many text fields to handle, you can define an extension method :
public static string ZeroIfEmpty(this string s)
{
return string.IsNullOrEmpty(s) ? "0" : s;
}
并像这样使用它:
Convert.ToDecimal(txtSample.Text.ZeroIfEmpty())
这篇关于字符串为空时,将字符串值替换为“ 0”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!