2012-10-05 66 views
1

在我的具體情況下,我需要propertyPriceTextBox中的值僅爲數字和整數。值也必須輸入,我可以只是Messagebox.Show()一個警告,這就是我需要做的。c#警告如果文本框爲空或包含非整數

這是我到目前爲止。

 private void computeButton_Click(object sender, EventArgs e) 
    { 
     decimal propertyPrice; 

     if ((decimal.TryParse(propertyPriceTextBox.Text, out propertyPrice))) 
      decimal.Parse(propertyPriceTextBox.Text); 
     { 

      if (residentialRadioButton.Checked == true) 



       commisionLabel.Text = (residentialCom * propertyPrice).ToString("c"); 



      if (commercialRadioButton.Checked == true) 

       commisionLabel.Text = (commercialCom * propertyPrice).ToString("c"); 

      if (hillsRadioButton.Checked == true) 

       countySalesTaxTextBox.Text = (hilssTax * propertyPrice).ToString("c"); 

      if (pascoRadioButton.Checked == true) 

       countySalesTaxTextBox.Text = (pascoTax * propertyPrice).ToString("c"); 

      if (polkRadioButton.Checked == true) 

       countySalesTaxTextBox.Text = (polkTax * propertyPrice).ToString("c"); 

      decimal result; 

       result = (countySalesTaxTextBox.Text + stateSalesTaxTextBox.Text + propertyPriceTextBox.Text + comissionTextBox.Text).ToString("c"); 
     } 

     else (.) 

      MessageBox.Show("Property Price must be a whole number."); 
    } 
+0

它已經有一段時間,但不將'TextBox'控制有一些內置的,將防止小數驗證功能? – neontapir

回答

3

而不是使用decimal.TryParse使用Int32.TryParse這將返回false,如果該值是一個非整數

int propertyPrice; 
if (Int32.TryParse(propertyPriceTextBox.Text, out propertyPrice) 
{ 
    // use propertyPrice 
} 
else 
{ 
    MessageBox.Show("Property Price must be a whole number."); 
} 

沒有必要再次打電話ParseTryParse執行轉換,如果它成功返回true否則返回false。

+0

謝謝你,你是一個令人難以置信的人。可能和超人一樣好。 –

0

可以實現這種方式

int outParse; 

    // Check if the point entered is numeric or not 
    if (Int32.TryParse(propertyPriceTextBox.Text, out outParse) && outParse) 
    { 
     // Do what you want to do if numeric 
    } 
    else 
    { 
     // Do what you want to do if not numeric 
    }