【问题标题】:c# warn if text box is empty or contains a non-whole numberc# 如果文本框为空或包含非整数,则发出警告
【发布时间】:2012-09-27 02:07:29
【问题描述】:

在我的具体情况下,我需要 propertyPriceTextBox 中的值只能是数字和整数。还必须输入一个值,我可以只 Messagebox.Show() 一个警告,这就是我需要做的。

这是我目前所拥有的。

        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.");
    }

【问题讨论】:

  • 已经有一段时间了,但是TextBox 控件不是有一些可以防止小数的内置验证功能吗?

标签: c# textbox string


【解决方案1】:

而不是使用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.");
}

无需再次调用Parse,因为TryParse 会进行转换,如果成功则返回true,否则返回false。

【讨论】:

  • 谢谢你,你是一个了不起的人。可能和超人一样好。
【解决方案2】:

你可以这样实现

   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
    }     

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-13
    • 2016-12-13
    • 2012-01-10
    • 1970-01-01
    • 2013-11-14
    • 2019-03-13
    • 1970-01-01
    • 2013-07-27
    相关资源
    最近更新 更多