而不只是检查空文本框Text属性可能/可能返回一个空字符串。所以你需要做的是使用string.IsNullOrWhiteSpace()
方法。
这里是你的代码更改为使用:
double total = 0;
if (string.IsNullOrWhiteSpace(TextBox1.Text))
TextBox1.Text = "0";
if (string.IsNullOrWhiteSpace(TextBox2.Text))
TextBox2.Text = "0";
if (string.IsNullOrWhiteSpace(TextBox3.Text))
TextBox3.Text = "0";
total = int.Parse(TextBox1.Text) * 0.10;
total = total + (int.Parse(TextBox2.Text) * 20);
total = total + (int.Parse(TextBox2.Text) * 30);
Lbl.Text = total.ToString();
但是,代码仍然是开放的bug。如果用户输入无法转换为int的字符串,该怎么办?要处理,你需要做这样的事情:
public static double CalcTotal() {
double total = 0;
var ints = ToInts(textBox1.Text, textBox2.Text, textBox3.Text);
var coef = new[] { 0.10d, 20, 30 };
for (int i = 0; i < ints.Length && i < coef.Length; i++) {
total += ints[i] * coef[i];
}
return total;
}
public static int[] ToInts(params string[] args) {
var res = new int[args.Length];
int i = 0;
foreach (var s in args) {
int num = 0;
int.TryParse(s, NumberStyles.None, CultureInfo.InvariantCulture, out num);
res[i++] = num;
}
return res;
}
尝试使用'String.IsNullOrEmpty(TextBoxN.Text)'进行空比较。 – 2015-04-03 10:28:19
向我们展示您的输入(文本框值)。 – 2015-04-03 10:31:49
也小心文化设置 – Caramiriel 2015-04-03 10:41:21