Reputation: 969
I'm trying to understand, how to write simple error message function, which would react if string was entered in text-boxes instead of numbers.
Let's say i want to calculate value 1 and value 2, but display error in label if string was entered.
EXAMPLE
1 + 1 = 2
a + 1 = error
My code
Calculate.cs
public static string ErrorMessage()
{
string msg = "";
try
{
//do sth
}
catch (Exception ex)
{
msg = "Wrong value";
}
return msg;
}
Calculator.asxc
protected void Button1_Click(object sender, EventArgs e)
{
try
{
//calculate - works
}
catch
{
Error.Text = Calculate.ErrorMsg();
}
Also tried sth like this, but doesn't seem to be working:
Calculate.cs
public static bool ErrorMessage(string value1, string value2)
{
bool check = true;
string error;
if (value1 != "" && value2 != "")
{
check = true;
}
if (value1 =="" || value2 =="")
{
check = false;
error = "Error!";
}
return check;
}
Calculator.asxc
protected void Button1_Click(object sender, EventArgs e)
{
try
{
//calculate - works
}
//
catch
{
bool res = false;
res = Calculate.ErrorMessage(textBox1.Text, textBox2.Text);
Error.Text = res.ToString();
}
I know that the second method doesn't check for numeric numbers, but i was just trying to implement some logic and see if ti works..but nothing does
I'm lost...please help
Upvotes: 1
Views: 318
Reputation: 2161
As I understand, you work with numbers ad want your application to display error message if user enters a string instead of number.
You should use Int32.Parse()
or Int32.TryParse()
methods.
More info about Parse and TryParse here.
Method TryParse is good enough as it doesn`t throw an error if it cannot parse string into integer, it returns false instead.
Here is example how to use this method in your classes, change Button1_Click method something like this:
protected void Button1_Click(object sender, EventArgs e)
{
int a;
int b;
// Here we check if values are ok
if(Int32.TryParse(textBox1.Text, out a) && Int32.TryParse(textBox2.Text, b))
{
// Calculate works with A and B variables
// don't know whats here as you written (//calculate - works) only
}
// If the values of textBoxes are wrong display error message
else
{
Error.Text = "Error parsing value! Wrong values!";
}
}
If you need to use ErrorMessage method, then here it is how you can change your ErrorMessage method, but this is more complex, the first example is easier:
public static string ErrorMessage(string value1, string value2)
{
int a;
int b;
// If we have an error parsing (note the '!')
if(!Int32.TryParse(value1, out a) || !Int32.TryParse(value2, b))
{
return "Error parsing value! Wrong values!";
}
// If everything is ok
return null;
}
Hope this helps, ask if you need more info.
Upvotes: 1