C#winform怎樣判斷輸入的資料格式??

Visual Studio 2010窗體設計中,很多時候要用到輸入數字。使用者在輸入的過程中,難免會出現輸入失誤的情況,如何讓程式判斷輸入的字元是不是數字呢?小編在此介紹一個方法,希望對廣大程式碼寫手們有所幫助。

C#winform怎樣判斷輸入的資料格式?

winform怎樣判斷輸入的資料格式?#

工具/原料

Visual Studio 2010

方法/步驟

開啟Visual Studio 2010,新建“解決方案”--新增“專案”

C#winform怎樣判斷輸入的資料格式?

winform怎樣判斷輸入的資料格式?#

窗體佈局:

1)3個lable控制元件;

2)3個textbox控制元件;

3)一個button控制元件;

C#winform怎樣判斷輸入的資料格式?

winform怎樣判斷輸入的資料格式?#

選中button按鈕--屬性--事件click(雙擊)

C#winform怎樣判斷輸入的資料格式?

winform怎樣判斷輸入的資料格式?#

在彈出的程式碼編輯框裡輸入程式碼:

private void btn_count_Click(object sender, EventArgs e)

{

int numberOne, numberTwo;

if (!int.TryParse(txt_number1.Text, out numberOne))

{

MessageBox.Show("第一個數輸入有誤,請重新輸入!");

txt_number1.Focus();

txt_number1.SelectAll();

return;

}

if (!int.TryParse(txt_number2.Text, out numberTwo))

{

MessageBox.Show("第二個數輸入有誤,請重新輸入!");

txt_number2.Focus();

txt_number2.SelectAll();

return;

}

this.txt_sum.Text = (numberOne + numberTwo).ToString();

}

C#winform怎樣判斷輸入的資料格式?

winform怎樣判斷輸入的資料格式?#

最後除錯看看,一切ok。

C#winform怎樣判斷輸入的資料格式?

winform怎樣判斷輸入的資料格式?#

注意事項

2、感謝您的拜讀,如果覺得不錯,順手給小彩的文章投上您寶貴的一票。謝謝!

程式碼, 數字, 資料格式,
相關問題答案