而不只是檢查空文本框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