C#if语句测试值是否不是数字

时间:2017-01-05 14:51:14

标签: c# winforms

我正在尝试将标签的.text保存到数据库,但有时该标签是无穷大符号。为了解决这个问题,我创建了一个if语句,用于检查标签是否为数字,然后抛出一个消息框告诉用户。但是,标签通常是十进制数字,if语句会抛出消息框。我想知道是否有人可以帮助我吗?

private void btnSaveResults_Click(object sender, EventArgs e)
{
    btnClearData.Enabled = true;


    if (System.Text.RegularExpressions.Regex.IsMatch(lblAerobicCap.Text, "[^0-9]"))
    {
        MessageBox.Show("Im sorry, there seems to have been an error in the inputting of the readings, please restart the test");

    }


    else
    {
        AthletesDetailsNew users = new AthletesDetailsNew();

        DateTime dateTimeVariable = DateTime.Now;

        users.Date_Of_Test = dateTimeVariable;
        users.First_Name = comboBoxFirstName.Text;
        users.Surname = comboBoxNewSurname.Text;
        users.Age = int.Parse(comboBoxAge.Text);
        users.Account_Number = int.Parse(comboBoxAccountNumber.Text);
        users.Aerobic_Capacity = /*Math.Truncate*/(decimal.Parse(lblAerobicCap.Text));


        DataClassDataContext dbCtx = new DataClassDataContext();

        dbCtx.AthletesDetailsNews.InsertOnSubmit(users);

        try
        {
            dbCtx.SubmitChanges();
            MessageBox.Show("Data saved");
        }

        catch
        {
            MessageBox.Show("Data failed to save");

        }
    }
}

5 个答案:

答案 0 :(得分:3)

您应该使用.TryParse()方法。

例如:

decimal value;
bool isNumber = Decimal.TryParse(inputVariable, out value);

答案 1 :(得分:2)

使用decimal.TryParse,以便在成功的情况下重复使用结果

decimal aerobicCap = -1;
if (!decimal.TryParse( lblAerobicCap.Text, out aerobicCap))
{
    MessageBox.Show("Im sorry, there seems to have been an error in the inputting of the readings, please restart the test");
}
else
{
   // code ...
   users.Aerobic_Capacity = aerobicCap;

答案 2 :(得分:0)

我认为在检查值是否为数字之前,您需要从lblAerobicCap.Text修剪空格。类似于lblAerobicCap.Text = lblAerobicCap.Text.Trim()

lblAerobicCap.Text = lblAerobicCap.Text.Trim();

if (System.Text.RegularExpressions.Regex.IsMatch(lblAerobicCap.Text, "[^0-9]"))
{
    MessageBox.Show("Im sorry, there seems to have been an error in the inputting of the readings, please restart the test");

}
[ ... ]

答案 3 :(得分:0)

最好还是避免用户输入任何数字。这样您就不必验证输入。

对于数字,请使用以下内容:

void Control_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!Char.IsDigit(e.KeyChar))
    {
        e.Handled = true;
    }
}

十进制:

void Control_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode != Keys.Decimal)
    {
        e.Handled = true;
    }
}

答案 4 :(得分:0)

我过去使用过一种扩展方法,对我很有用:

SQL Injection