2015-04-03 69 views
0

我想計算3個文本框的值。如果一個文本框爲空,則不必爲所有3個文本框輸入輸入內容,而應該計算剩餘的兩個文本框。我收到這個錯誤「輸入字符串格式不正確」的文本框,我沒有給出輸入。如果其中一個文本框爲空,如何計算文本框的值?

這是我的代碼

double total = 0; 
     if (TextBox1.Text == null) 
      TextBox1.Text = "0"; 
     if (TextBox2.Text== null) 
      TextBox2.Text = "0"; 
     if (TextBox3.Text == null) 
      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(); 
+0

嘗試使用'String.IsNullOrEmpty(TextBoxN.Text)'進行空比較。 – 2015-04-03 10:28:19

+0

向我們展示您的輸入(文本框值)。 – 2015-04-03 10:31:49

+0

也小心文化設置 – Caramiriel 2015-04-03 10:41:21

回答

1

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

輸入一個字符串,所以你需要將驗證或嘗試下面的代碼

 double total = 0; 
     total = TryConvert(TextBox1.Text) * 0.10; 
     total = total + (TryConvert(TextBox2.Text) * 20); 
     total = total + (TryConvert(TextBox2.Text) * 30); 
     Lbl.Text = total.ToString(); 

    public int TryConvert(string s) 
    { 
     int i = 0; 
     int.TryParse(s, out i); 
     return i; 
    } 
0

您應該檢查文本是否爲空(除了檢查空值)。

例如,

string.IsNullOrEmpty(Textbox1.Text) 

而轉換值您可以使用的TryParse。

例如,

int textBox1Value = 0; 
int.TryParse(text, out textBox1Value); 
0

你還要TextBox2.Text兩次順便說一下,我想你的意思TextBox3.Text!由於您正在計算雙倍數,因此您可能會考慮使用double.Parse而不是int.Parse

0

嘗試:

if (TextBox3.Text == null||TextBox3.Text == "") 
      TextBox3.Text = "0"; 

文本框始終爲 「」,而不是空。

+0

是的..謝謝 – sharanya 2015-04-03 11:56:58

+0

@sharanya從所有其他答案,你會發現這一個是最好的一個:D如果TextBox3.Text ==「aisiktir」 – 2015-04-03 12:04:23

+0

這是不是完整的解決方案! – yogi970 2015-04-03 12:05:39

相關問題