Nguyễn Mạnh Cường Nguyễn Mạnh Cường - 20 days ago 6
C# Question

Show "Math error" to textbox when click a button with error

I want to make a function in a math button when it have an error the text box will display "Math error" for example: when i click "Abs" button without number before, the text box will show "Math error" until i click a number then "Abs" button the text box will show the result. The code have no problem, i just want to add more. this first time when i click button "Abs" without number it show "Math error" that i need but when i click again it show error.

private void btnAbs_Click(object sender, EventArgs e)
{
double abs;
if(txtND.Text != string.Empty)
{
No1 = Convert.ToDouble(txtND.Text);
abs = Math.Abs(No1);
txtND.Text = abs.ToString();
inputStatus = false;
}
if(txtND.Text == string.Empty)
{
txtND.Text = "Math Error";
inputStatus = false;
}
//inputStatus = false;
}


this is the picture of problem

Answer

Convert.ToDouble fail with text input, try as below

double dval;
double abs;
if(string.IsNullOrEmpty(txtND.Text))
{
    txtND.Text = "Empty Input"; 
}else if (double.TryParse(txtND.Text.Trim(), out dval))
{
    abs = Math.Abs(dval);
    txtND.Text = abs.ToString();
}
else
{
    txtND.Text = "Math Error";
}
Comments