I am trying to catch FormatException
from a text box. For example - if user enters number or any other character inside name text box field. Message will pop up - something went wrong. I'm fairly new to C# and I don't understand the concept of exceptions. Below does not work. What is correct exception for invalid format?
private void button1_Click(object sender, EventArgs e)
{
try
{
string name = textBox1.Text;
int age = int.Parse(textBox2.Text);
}
catch (FormatException )
{
MessageBox.Show("Something went wrong");
}
Try this to show the message.
try
{
double mydoubleParam = 0;
// Assuming textBox1.Text is Name test box
if (double.TryParse(textBox1.Text, out mydoubleParam))
{
new Exception(" Numeric value in name field");
}
int age = int.Parse(textBox2.Text);// Assuming Number text box
MessageBox.Show("How are you today?");
}
catch (FormatException ex)
{
MessageBox.Show("Something went wrong");
}
you can handle it in the TextChanged event like this:
private void textBox1_TextChanged(object sender, EventArgs e)
{
int a;
bool isNumeric = int.TryParse(textBox1.Text, out a);
if (isNumeric)
{
MessageBox.Show("Something went wrong");
}
}
catch (FormatException ex)
{
MessageBox.Show("Something went wrong " + ex.ToString() );
}
USE ex as variable in Catch.
UPDATE (As per comment )
catch (FormatException ex)
{
MessageBox.Show("Something went wrong !");
}
If you need to check for numbers inside the name textbox, then:
try {
string name = textBox1.Text;
Regex regex = new Regex("[0-9]");
if (regex.IsMatch(name)) {
throws new FormatException();
}
int age = int.Parse(textBox2.Text);
MessageBox.Show("How are you today?");
}
catch (FormatException) {
MessageBox.Show("Something went wrong");
}
You should also show a more specific message for each of the cases.
UPDATE
What you should really be doing is:
var regex = new Regex("[0-9]");
if (regex.IsMatch(textBox1.Text)) {
MessageBox.Show("There was a number inside name textbox.","Error in name field!");
return;
}
try {
Convert.ToInt32(textBox2.Text);
} catch (Exception) {
MessageBox.Show("The input in age field was not valid","Error in name field!");
return;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.