了解 TryParse:
TryParse靜態方法用來將字符串轉換成對應類型的數值。
所以int.TryParse()是將字符串轉換為int類型的,如果成功返回true,失敗返回false。
private void button1_Click(object sender, EventArgs e) { int tmp; string t1 = textBox1.Text; if (!int.TryParse(t1, out tmp))//如果轉換失敗(為false)時輸出括號內容 { MessageBox.Show("請正確輸入數字"); } else { MessageBox.Show("輸入的數字是:"+t1); //成功時輸出數字 } }
也可以用try catch方法測試。但是前輩說效率較低。
private void button1_Click(object sender, EventArgs e) { string t1 = textBox1.Text; int tmp; try { tmp = int.Parse(t1); MessageBox.Show("輸入的數字是:" + t1); }//轉換成功說明是數字,並輸出數字 catch { MessageBox.Show("請正確輸入數字"); }//轉換失敗 }