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

标签 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");

        }
    }
}

最佳答案

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

例如:

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

关于C# if 语句来测试值是否不是数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41487967/

相关文章:

c# - 如何从 C# 中的 IDataReader Func 调用的另一个类中访问一个类属性

c# - 检查 ListView 中具有巨大列表项的所有项目?

.net - WInforms Combobox SelectionChangeCommitted 事件并不总是改变 SelectedValue

c# - 为什么我的 backgroundWorker 不工作?

c# - 如何在窗体上显示必填字段

c# - 大文件的 Windows fsync (FlushFileBuffers) 性能

c# - 从 URL 打开 XmlDocument

c# - 从 WPF 调用进程执行时间太长

c# - EF : Should I include foreign key ID's in my entities?

c# - 无法保存对数据库的更改