如果文本框的null值是double值,我必须得到一条消息

时间:2019-07-09 11:52:46

标签: c#

如果文本框具有双精度值的空值,我必须得到一条消息,我尝试了以下代码,但是在第二种情况下出现错误,请帮忙!

acno = Txtacc.Text;
recoverymoney = double.Parse(Txtamount.Text);

if (string.IsNullOrEmpty(this.Txtacc.Text))
{
    MessageBox.Show("You have not entered account number, Please Enter it...!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (string.IsNullOrEmpty(this.Txtamount.Text))
{
    MessageBox.Show("You have not entered amount, Please Enter it..!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

2 个答案:

答案 0 :(得分:2)

您应该使用double.TryParse进行此操作,并且应该在检查后实际读取这些值:

if (string.IsNullOrEmpty(this.Txtacc.Text))
{
    MessageBox.Show("You have not entered account number, Please Enter it...!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (string.IsNullOrEmpty(this.Txtamount.Text))
{
    MessageBox.Show("You have not entered amount, Please Enter it..!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
eise if(!double.TryParse(this.Txtamount.Text, out recoverymoney ))
{
    MessageBox.Show("You have entered an invalid amount, Please Enter a number..!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
acno = Txtacc.Text

答案 1 :(得分:0)

if (string.IsNullOrEmpty(this.Txtacc.Text)) {
  MessageBox.Show("You have not entered account number, Please Enter it...!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
} else if (!myDbContect.Accounts.Any(a => a.AccountNumber == this.Txtacc.Text)) {
  MessageBox.Show("You have not entered a valid account number, Please Enter it...!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
} else if (!double.TryParse(Txtamount.Text, out double myrecoverymoney)) {
  MessageBox.Show("The amount value you entered is not parseable to a double.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
// do something with account and myrecoverymoney

并且更喜欢使用小数表示货币,金额等,而不是双精度。