Exception Handling C# - c#

I am relatively new at this and have been racking my brain attempting to get my program to work properly and it just won't. I am working in Visual Studio 2012 C# on a Forms Application.
I need it to produce a distinct error message when the user input value is more than 0 but less than 10,000. It also must produce a distinct error message when the user enters a non-numeric value and a distinct error message when the user fails to enter any value at all.
The code I've written so far produces a distinct error message when the user enters a non-numeric value or when they fail to enter any value at all, but it does not trigger an error message when the user enters a value that is below or over the required range.
It is as if the compiler is ignoring the code I've written for the first exception/overflow exception and only recognizing the code for the second and final exception. My code has no coding errors. It appears that my problem is in the logic.
Please help me if you can. My code is below thanks!
private void btnCalculate_Click(object sender, System.EventArgs e)
{
try
{
{
decimal subtotal = Convert.ToDecimal(txtSubtotal.Text);
decimal discountPercent = .25m;
decimal discountAmount = subtotal * discountPercent;
decimal invoiceTotal = subtotal - discountAmount;
lblDiscountPercent.Text = discountPercent.ToString("p1");
lblDiscountAmount.Text = discountAmount.ToString("c");
lblTotal.Text = invoiceTotal.ToString("c");
}
}
catch (OverflowException)
{
decimal subtotal = Convert.ToDecimal(txtSubtotal.Text);
if (subtotal <= 0)
{
MessageBox.Show("Subtotal must be greater than $0.00. ", "Error Entry");
txtSubtotal.Focus();
}
if (subtotal >= 10000)
{
MessageBox.Show("Subtotal must be less than $10000.00. ", "Error Entry");
txtSubtotal.Focus();
}
}
catch (Exception)
{
if (txtSubtotal.Text == "")
{
MessageBox.Show("Subtotal is a required field. ", "Error Entry");
}
else
{
MessageBox.Show(
"Please enter a valid Number for the subtotal field.", "Error Entry");
txtSubtotal.Focus();
}
}
}
private void btnExit_Click(object sender, System.EventArgs e)
{
this.Close();
}
private void txtSubtotal_TextChanged(object sender, EventArgs e)
{
}
}
}

I would used KeyEvent press enter or Leave event for this, first I need to create generic class for verification if the input from the user is not a string.
Condition:
1 verify if the input is not a string Im using generic for general purposes class.
public class iCnF()
{
public static System.Boolean IsNumeric(System.Object Expression)
{
if (Expression == null || Expression is DateTime)
return false;
if (Expression is Int16 || Expression is Int32 || Expression is Int64 || Expression is Decimal || Expression is Single || Expression is Double || Expression is Boolean)
return true;
try
{
if(Expression is string)
Double.Parse(Expression as string);
else
Double.Parse(Expression.ToString());
return true;
} catch {} // just dismiss errors but return false
return false;
}
}
Then I need to verify if the input is not empty
private void txtSubtotal_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Tab)
{
if (txtSubtotal.Text.Length > 0)
{
bool sd = iCnF.IsNumeric(txtSubtotal.Text);
if (sd == false)
{
MessageBox.Show("Subtotal must be a numeric value. ", "Error Entry");
txtSubtotal.Clear();
txtSubtotal.Focus();
}
else
{
decimal subtotal = Convert.ToDecimal(txtSubtotal.Text);
if (subtotal <= 0)
{
MessageBox.Show("Subtotal must be greater than $0.00. ", "Error Entry");
txtSubtotal.Focus();
}
if (subtotal >= 10000)
{
MessageBox.Show("Subtotal must be less than $10000.00. ", "Error Entry");
txtSubtotal.Focus();
}
}
}
else
{
MessageBox.Show("Subtotal must not be empty. ", "Error Entry");
txtSubtotal.Focus();
}
}
}
if not empty and numberic value my subtotal <= 0 and subtotal >= 10000
Hope this will help you :D

As I already mentioned in comment you should consider moving your code out of catch block.
In this case you should think of creating a simple method which will validate your input and produces output message.
An example is for you:
private bool IsPageValid()
{
string errorMessage = string.Empty;
bool isValid = true;
if (subtotal <= 0)
{
errorMessage+="<li>"+"<b>Subtotal must be greater than $0.00. ", "Error Entry"+ "</b><br/>";
txtSubtotal.Focus();
isValid=false;
}
}
Likewise write other clause of validations in this function..This will validate each of your condition and if fails it would make the isValid false thus not allowing users to submit.
Now you should call this function in your button click.
protected void btnSubmit_Click(object sender, EventArgs e)
{
ClearMessage();
if (IsPageValid().Equals(true))
{
// allow next action to happen.
}
}

Code should look like this
try {
decimal subtotal = Convert.ToDecimal(txtSubtotal.Text);
try {
if(x<0 || x>10000){
throw new OverFlowException("");
}
//Do what ever you want
}
catch(Exception ex){
// catch overflow
}
}
catch(Exception ex){
// catch nonnumeric value
}

Related

C# if statement to test if value is not a number

I am trying to save the .text of a label to a database but sometimes that label is an infinity symbol. To catch for this I have created an if statement which checks if the label is a number or not and throws a message box up to tell the user. However more often than not the label will be a decimal number and the if statement throws up the message box. I was wondering if anyone could help me out please?
private void btnSaveResults_Click(object sender, EventArgs e)
{
btnClearData.Enabled = true;
if (System.Text.RegularExpressions.Regex.IsMatch(lblAerobicCap.Text, "[^0-9]"))
{
MessageBox.Show("Im sorry, there seems to have been an error in the inputting of the readings, please restart the test");
}
else
{
AthletesDetailsNew users = new AthletesDetailsNew();
DateTime dateTimeVariable = DateTime.Now;
users.Date_Of_Test = dateTimeVariable;
users.First_Name = comboBoxFirstName.Text;
users.Surname = comboBoxNewSurname.Text;
users.Age = int.Parse(comboBoxAge.Text);
users.Account_Number = int.Parse(comboBoxAccountNumber.Text);
users.Aerobic_Capacity = /*Math.Truncate*/(decimal.Parse(lblAerobicCap.Text));
DataClassDataContext dbCtx = new DataClassDataContext();
dbCtx.AthletesDetailsNews.InsertOnSubmit(users);
try
{
dbCtx.SubmitChanges();
MessageBox.Show("Data saved");
}
catch
{
MessageBox.Show("Data failed to save");
}
}
}
You should use the .TryParse() method for this.
for example:
decimal value;
bool isNumber = Decimal.TryParse(inputVariable, out value);
Use decimal.TryParse so in case of success you can reuse the result
decimal aerobicCap = -1;
if (!decimal.TryParse( lblAerobicCap.Text, out aerobicCap))
{
MessageBox.Show("Im sorry, there seems to have been an error in the inputting of the readings, please restart the test");
}
else
{
// code ...
users.Aerobic_Capacity = aerobicCap;
I think you need to trim the spaces from lblAerobicCap.Text prior to checking if the value is a number. Something like lblAerobicCap.Text = lblAerobicCap.Text.Trim().
lblAerobicCap.Text = lblAerobicCap.Text.Trim();
if (System.Text.RegularExpressions.Regex.IsMatch(lblAerobicCap.Text, "[^0-9]"))
{
MessageBox.Show("Im sorry, there seems to have been an error in the inputting of the readings, please restart the test");
}
[ ... ]
Better still avoid users entering anything but numbers. That way you do not have to validate the input.
For the digits use something like this:
void Control_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
Decimal:
void Control_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode != Keys.Decimal)
{
e.Handled = true;
}
}
I have used an extension method in the past which works nicely for me:
public static bool IsNumber(this object value)
{
return value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is int
|| value is uint
|| value is long
|| value is ulong
|| value is float
|| value is double
|| value is decimal;
}
object testObject = 0.1;
if (testObject.IsNumber()) { MessageBox.Show("Hooray!"); }

IF Boolean statement order of input validation

I have to validate some inputs the user makes, and send a error message
this is what I got so far
// probes the methods to check for validity.
private void btnCalculate_Click(object sender, EventArgs e)
{
if (!(ValidWidth(float.Parse(txtWidth.Text))))
{
return;
}
if (!(ValidLength(float.Parse(txtLength.Text))))
{
return;
}
if (!(ValidDepth(float.Parse(txtAvgDepth.Text))))
{
return;
}
}
My problem is when I enter the values into Length, Width, and Depth. It only does it in order..what I mean is if I don't enter a width and leave it blank and put in length and depth it gives me a unhandled expection.
here are my methods
/** Created a boolean method to test if the written width is valid OR not valid **/
private bool ValidWidth(float Width1) {
float Width = float.Parse(txtWidth.Text);
{
if (Width >= 2 & Width <= 20)
{
return true;
}
else
{
string Title = "Data Invalid";
string Msg = "Width Measurement is invalid \n Place enter a value between 2 and 20";
DialogResult Response;
Response = MessageBox.Show(Msg, Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return false;
}
}
}
/** Created a boolean method to test if the written legnth is valid OR not valid **/
private bool ValidLength(float Length1)
{
float Length = float.Parse(txtLength.Text);
{
if (Length >= 5 & Length <= 50)
{
return true;
}
else
{
string Title = "Data Invalid";
string Msg = "Legnth Measurement is invalid \n Place enter a value between 5 and 50";
DialogResult Response;
Response = MessageBox.Show(Msg, Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return false;
}
}
}
/** Created a boolean method to test if the written legnth is valid OR not valid **/
private bool ValidDepth(float Depth1)
{
float Depth = float.Parse(txtAvgDepth.Text);
if (Depth >= 2 & Depth <= 4)
{
return true;
}
else
{
string Title = "Data Invalid";
string Msg = "Average Depth Measurement is invalid \n Place enter a value between 2 and 4";
DialogResult Response;
Response = MessageBox.Show(Msg, Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return false;
}
}
The Parse method will throw an exception if you feed it an empty string. You should catch that exception, or use TryParse.
You messed up every thing in your code. first there is a method float.TryParse which attempts to convert your string into float number. but it will not throw an exception if conversion failed. instead it gives a boolean value which tells parse succeeded or not.
I think this is better.
private void btnCalculate_Click(object sender, EventArgs e)
{
if(!ValidateWidth(txtWidth.Text) ||
!ValidateLength(txtLength.Text) ||
!ValidateDepth(txtAvgDepth.Text)) // if any of these failed
{
MessageBox.Show(Msg, Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
I write ValidateWidth for you as an example.
private string Title = "Data Invalid";
private string Msg;
private bool ValidateWidth(string input)
{
float width;
if(float.TryParse(input, out width))
{
if (Width >= 2 && Width <= 20)
{
return true;
}
}
Msg = "Width Measurement is invalid \n Place enter a value between 2 and 20";
return false;
}

Textbox null value when parsing and messagebox notification

I have made a form which works perfectly fine when the fields are filled in. If you click the "convert" button with a blank textbox, it throws an error due to parsing a null value.
Obviously this means that I've declared my variable upon the button click.
I would also like a message box to pop up if the field is empty, to prompt the user to enter data.
Here is the code I have for the convert button:
private void exitButton_Click(object sender, EventArgs e)
{
//closes the form
this.Close();
}
private void convertButton_Click(object sender, EventArgs e)
{
decimal measurementDecimal = decimal.Parse(enterTextBox.Text);
//if else arguments for radio buttons
if (string.IsNullOrWhiteSpace(enterTextBox.Text))
{
MessageBox.Show("Please enter a value");
}
else if (inchesFromRadioButton.Checked && (inchesToRadioButton.Checked))
{
convertedTextBox.Text = measurementDecimal.ToString();
}
else if (inchesFromRadioButton.Checked && (feetToRadioButton.Checked))
{
convertedTextBox.Text = (measurementDecimal / 12).ToString();
}
else if (inchesFromRadioButton.Checked && (yardsToRadioButton.Checked))
{
convertedTextBox.Text = (measurementDecimal / 36).ToString();
}
else if (feetFromRadioButton.Checked && (inchesToRadioButton.Checked))
{
convertedTextBox.Text = (measurementDecimal * 12).ToString();
}
else if (feetFromRadioButton.Checked && (feetToRadioButton.Checked))
{
convertedTextBox.Text = measurementDecimal.ToString();
}
else if (feetFromRadioButton.Checked && (yardsToRadioButton.Checked))
{
convertedTextBox.Text = (measurementDecimal / 3).ToString();
}
else if (yardsFromRadioButton.Checked && (inchesToRadioButton.Checked))
{
convertedTextBox.Text = (measurementDecimal * 36).ToString();
}
else if (yardsFromRadioButton.Checked && (feetToRadioButton.Checked))
{
convertedTextBox.Text = (measurementDecimal * 3).ToString();
}
else if (yardsFromRadioButton.Checked && (yardsToRadioButton.Checked))
{
convertedTextBox.Text = measurementDecimal.ToString();
}
else
{
MessageBox.Show("Parameters not set. Please select a 'From' and 'To'");
}
Solution 1 : You can perform null or empty check before parsing the input value.and if it is invalid display warning and return from the method.
Try This:
private void convertButton_Click(object sender, EventArgs e)
{
//if else arguments for radio buttons
if (string.IsNullOrWhiteSpace(enterTextBox.Text))
{
MessageBox.Show("Please enter a value");
return;
}
/*Your remaining code here*/
decimal measurementDecimal = decimal.Parse(enterTextBox.Text);
Solution 2: You can use decimal.TryParse() method for checking the valid decimal value.
From MSDN:
Converts the string representation of a number to its Decimal
equivalent. A return value indicates whether the conversion succeeded
or failed.
private void convertButton_Click(object sender, EventArgs e)
{
decimal measurementDecimal ;
if (!decimal.TryParse(enterTextBox.Text,out measurementDecimal))
{
MessageBox.Show("Please enter a valid value");
return;
}
else
{
/*Your remaining code here*/
}

How can I make a code that will check if a string isn't a number

The question says it all
What I tried to do was
if (textbox1.Text != int)
{
MessageBox.Show ("This is not a proper number.")
}
I use a button to start the command.
I am new to C# so excuse such a possibly easy
This will get the number for you and tell you if it's not valid. Also it won't throw an exception if it's not valid. It'll just return false.
int i;
if(!int.TryParse("Your_String_To_Try_And_Parse", out i)) {
MessageBox.Show("Not a number");
}
Now the drawback to this is that it will tell you if it's an integer not a decimal etc. so 5.5 is not valid.
Call int.TryParse() and evaluate the returned result.
in this i am performing addition of no ad if i enter string then it will get concatinated
private void button1_Click(object sender, EventArgs e)
{
bool chk,chk1;
int chkq;
chk = int.TryParse(textBox1.Text, out chkq);
chk1 = int.TryParse(textBox2.Text, out chkq);
if (chk1 && chk)
{
MessageBox.Show("Is number");
}
else
{
MessageBox.Show("Not a number");
}
}

Not allow zero in textbox

I need a textbox which only the user can permit to enter integers. But the user can't enter zero. i.e, he can enter 10,100 etc. Not 0 alone.
How can I make event in KeyDown?
The way you plan to do this, is very annoying for a user. You're guessing what a user wants to enter, and act upon your guess, but you can be so wrong.
It also has holes, for example, a user can enter "10" and then delete the "1". Or he could paste in a "0" -- you do allow paste, don't you?
So my solution would be: let him enter any digit he likes, any way he likes, and validate the input only after he finished, for example, when the input loses focus.
Why not using a NumericUpDown and make the following settings:
upDown.Minimum = 1;
upDown.Maximum = Decimal.MaxValue;
Use int.TryParse to convert the text into a number and check if that number is not 0. Use the Validating event for the check.
// this goes to you init routine
textBox1.Validating += textBox1_Validating;
// the validation method
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (textBox1.Text.Length > 0)
{
int result;
if (int.TryParse(textBox1.Text, out result))
{
// number is 0?
e.Cancel = result == 0;
}
else
{
// not a number at all
e.Cancel = true;
}
}
}
EDIT:
Okay, since you use WPF you should take a look at how to implement validation the WPF way. Here is a validation class that implements the above logic:
public class StringNotZeroRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (textBox1.Text.Length == 0)
return new ValidationResult(true, null);
int result;
if (int.TryParse(textBox1.Text, out result))
{
// number is 0?
if (result == 0)
{
return new ValidationResult(false, "0 is not allowed");
}
}
else
{
// not a number at all
return new ValidationResult(false, "not a number");
}
return new ValidationResult(true, null);
}
}
This is another variation on the theme:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
char newChar = Convert.ToChar(e.KeyValue);
if (char.IsControl(newChar))
{
return;
}
int value;
e.SuppressKeyPress = int.TryParse((sender as TextBox).Text + newChar.ToString(), out value) ? value == 0 : true;
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (textBox1.Text == "" && e.KeyChar == '0')
{
e.Handled = true;
return;
}
if (e.KeyChar < '0' || e.KeyChar > '9')
{
e.Handled = true;
return;
}
}
not nice but it works

Categories

Resources