'How do I create a custom error message with a try/catch block in C#?
I'm doing a simple order total calculation function and I'm trying to figure out how to display a custom error message when the user input is the incorrect format. I.e. when they enter a non-integer in txtJava.Text, the message will display "Please enter an integer for Java"
private void btnSubmit_Click(object sender, EventArgs e)
{
int Java;
int Latte;
int Mocha;
int Frappe;
string Name = txtName.Text;
double javaPrice = 1.25;
double mochaPrice = 2.95;
double lattePrice = 2.75;
double frappePrice = 3.25;
double dblTaxRate = .09;
double dblSubtotal;
double dblTax;
double dblTotal;
txtMessage.Text = "Thank you " + Name + " for your order!";
Java = Convert.ToInt32(txtJava.Text);
Latte = Convert.ToInt32(txtLatte.Text);
Mocha = Convert.ToInt32(txtMocha.Text);
Frappe = Convert.ToInt32(txtFrappe.Text);
dblSubtotal = Java * javaPrice + Mocha * mochaPrice + Frappe * frappePrice + Latte * lattePrice;
dblTax = dblSubtotal * dblTaxRate;
dblTotal = dblSubtotal + dblTax;
txtSubtotal.Text = dblSubtotal.ToString("C2");
txtTax.Text = dblTax.ToString("C2");
txtTotal.Text = dblTotal.ToString("C2");
Solution 1:[1]
Avoid using try Prase or try catch in this scenario. It is better to change the textbox input type to be a number only.
I can't see what type of application you are running, but if its a webForms application you could alter the markup to look something like this:
<input type="number" id="quantity" name="quantity" min="1" max="100">
If its a WPF application: Allow only numeric entry in WPF Text Box
If this doesn't help you may need to provide more code. Give us a bit more context.
Happy coding.
Solution 2:[2]
This code, instead of Java = Convert.ToInt32(txtJava.Text);
if (!TryParse(txtJava.Text, Java)) {
//Display the text you want
}
In addition, your variables are not with the same naming convention ;)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | DharmanBot |
| Solution 2 | Dylan Barquilla |
