2012-06-28 46 views
3

我正在構建這個C#窗口應用程序。在特定的窗體上,我使用maskedtextbox輸入最多3個數字,然後將其轉換爲int,因爲我必須使用插入查詢將所有這些數據發送到數據庫,但問題是這些maskedtextboxes留空時發生錯誤:如何將maskedtextbox值轉換爲int,如果它是空的?

int scd_user_comm = Convert.ToInt32(maskedTextBox1.Text); 

和錯誤是:

輸入字符串的不正確的格式。

數據庫中的相應字段允許爲空,所以如果留空,它不能給出錯誤。任何人都可以幫忙嗎?

單方面的問題::我可以使用文本框或maskedtextbox來確保用戶只輸入數字值b/w 0到100?提前致謝。

+0

更新來自其中一個答案的代碼,然後將scd_user_comm更改爲其他內容。 Plain System.Int32類型不能包含空值(如果您的數據庫支持該字段的NULL,則NULL和0是不同的)。 –

+0

有兩種方法,使用TryParse或檢查String.IsNullOrEmpty() –

回答

2

你可以嘗試Int32.TryParse()方法

int scd_user_comm; 
if(Int32.TryParse(maskedTextBox1.Text, out scd_user_comm) == false) 
    scd_user_comm = 0; 

這會給你所有你的整數變種工作所需的flexiblity和maschedTextBox-

強制您的maskTextBox只接受數值集

maskTextBox1.Mask = "999"; 
    maskTextBox1.TextMaskFormat = MaskFormat.ExludePromptAndLiterals; 

然而,這不足以確保照耀處數爲0和100之間 爲了得到這樣的結果,你需要使用驗證事件,並拒絕輸入,如果是自己的極限之外

private void maskedTextBox1_Validating(object sender, CancelEventArgs e) 
    { 
     int num; 
     if (Int32.TryParse(maskedTextBox1.Text, out num) == true) 
     { 
      if (num < 0 || num > 100) 
      { 
       MessageBox.Show("Insert number between 0 and 100"); 
       e.Cancel = true; 
      } 
     } 
    } 
+0

轉換失敗後'scd_user_comm'的值將爲'0'。 這就是爲什麼你只需要'Int32.TryParse(maskedTextBox1.Text,out scd_user_comm)'而不是第二和第三行。 – Smileek

+0

不需要將** 0 **分配給*** scd_user_comm ***變量。 – adatapost

+0

好吧,但這只是一個例子來解釋TryParse – Steve

1

您可以使用的TryParse來代替:

int scd_user_comm; 
if(!Int32.TryParse(maskedTextBox1.Text, out scd_user_comm)) 
{ 
    // Do something to notify the user that the text isn't a number. 
} 
+0

實際的問題是,如果用戶離開maskedtextbox爲空,它會給出錯誤,它不會將其轉換爲 –

+0

TryParse方法就像Parse方法,除了如果轉換失敗,TryParse方法不會引發異常。它消除了在s無效並且無法成功解析的情況下使用異常處理來測試FormatException的需求。 http://msdn.microsoft.com/en-us/library/f02979c7.aspx – Smileek

+0

@ user1479153 - Smileek是對的。在if子句中,如果你願意,你可以做你的數據庫邏輯。 TryParse從不拋出,只是由於嘗試將值轉換爲Int而返回true/false。 –