input validation after if statement - c#

When trying a regular expression for no characters my winforms EnterValue is still being triggered after the if statement, how can I stop it from going any further after the trigger?
private void EnterValue_Click(object sender, EventArgs e)
{
if (textBox1.Text != string.Empty && !Regex.IsMatch(textBox1.Text, #"^[0-9]+$"))
{
MessageBox.Show("Please only enter numbers");
textBox1.Clear();
}
//convert input to double
listDouble.Add(Convert.ToDouble(textBox1.Text)); // this line still throws exception
textBox1.Clear();
//clear existing items
listBox1.Items.Clear();
// clear any existing list items
for (int i = 0; i < listDouble.Count; i++)
{
listBox1.Items.Add(listDouble[i]);
}
//for each value added, add this to our list
}

Return from the method:
if (textBox1.Text != string.Empty && !Regex.IsMatch(textBox1.Text, #"^[0-9]+$"))
{
MessageBox.Show("Please only enter numbers");
textBox1.Clear();
return; // nothing after this will execute
}
This will execute only if the if predicate is true, and the method will return as soon as the return; statement has been hit, without any of the other code being run.

First option is to use return:
if (textBox1.Text != string.Empty && !Regex.IsMatch(textBox1.Text, #"^[0-9]+$"))
{
MessageBox.Show("Please only enter numbers");
textBox1.Clear();
return; // exit method
}
Second option is to use else:
if (textBox1.Text != string.Empty && !Regex.IsMatch(textBox1.Text, #"^[0-9]+$"))
{
MessageBox.Show("Please only enter numbers");
textBox1.Clear();
}
else
{
// your statements
}

Use Decimal.TryParse. And use return after checking condition to exit from current method:
The return statement terminates execution of the method in which it appears and returns control to the calling method.
Decimal dec;
if (!Decimal.TryParse(textBox1.Text, out dec))
{
MessageBox.Show("Please only enter numbers");
textBox1.Clear();
return;
}

Related

Adding integers to list using sorted and unsorted radio buttons C#

I have a program that adds integers to a list via a text box and button. I also want to include 2 radio buttons that allow the user to either add an item to the listbox in a sorted manner, or in an unsorted manner. This is the code I have so far -
private void btnInsert_Click(object sender, EventArgs e)
{
int acceptedNum = 0;
if (!string.IsNullOrEmpty(txtInsert.Text))
{
if (!(lstIntegers.Items.Contains(txtInsert.Text)))
{
if (!(int.TryParse(txtInsert.Text, out acceptedNum) && acceptedNum <=0 || acceptedNum >= 100))
{
lstIntegers.Items.Add(txtInsert.Text);
txtInsert.Clear();
txtInsert.Focus();
bubbleSort();
}
else
{
MessageBox.Show("Please input value between 1-100", "error", MessageBoxButtons.OK);
txtInsert.Text = "";
txtInsert.Focus();
return;
}
}
else
{
MessageBox.Show("Number already exists in list", "error", MessageBoxButtons.OK);
}
}
else
{
MessageBox.Show("Please input value between 1-100", "error", MessageBoxButtons.OK);
txtInsert.Focus();
return;
}
if (lstIntegers.Items.Count == 30)
{
MessageBox.Show("Maximum number of entries exceeded", "error", MessageBoxButtons.OK);
//button enabled was false however couldn't then add another
btnInsert.Enabled = true;
}
if (radSorted.Checked)
lstIntegers.Items.Add(SortedList < SortOrder>);
}
the lines
if (radSorted.Checked)
lstIntegers.Items.Add(SortedList < SortOrder>);
are giving me an error, does anyone have any idea how to make a statement so its 'if user has selected radSorted (radio button sorted), then add integer to sorted list. Else if user has checked radUnsorted (radio button unsorted), then add integer to end of list?
Thanks.
I think if you change these parts your program will work.
change this part:
bubbleSort();
to this:
if (radSorted.Checked) bubbleSort();
and then remove these lines:
if (radSorted.Checked)
lstIntegers.Items.Add(SortedList < SortOrder>);

Exception Handling 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
}

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");
}
}

C# Textbox validation should only accept integer values, but allows letters as well

if (textBox1.Text != "") // this forces user to enter something
{
// next line is supposed to allow only 0-9 to be entered but should block all...
// ...characters and should block a backspace and a decimal point from being entered....
// ...but it is also allowing characters to be typed in textBox1
if(!IsNumberInRange(KeyCode,48,57) && KeyCode!=8 && KeyCode!=46) // 46 is a "."
{
e.Handled=true;
}
else
{
e.Handled=false;
}
if (KeyCode == 13) // enter key
{
TBI1 = System.Convert.ToInt32(var1); // converts to an int
Console.WriteLine("TBI1 (var1 INT)= {0}", var1);
Console.WriteLine("TBI1= {0}", TBI1);
}
if (KeyCode == 46)
{
MessageBox.Show("Only digits...no dots please!");
e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
}
}
else
{
Console.WriteLine("Cannot be empty!");
}
// If I remove the outer if statement and skip checking for an empty string, then
// it prevents letters from being entered in the textbox. I need to do both, prevent an
// empty textbox AND prevent letters from being entered.
// thanks, Sonny5
You didn't specify where this code runs, but my assumption would be it runs on key down. Since key down is received before the character is processed and the Text property is updated, your check for .Text == "" will prevent the rest of the validation running, at least for the first character.
You should move the check for empty value on a different event than the check for the key pressed.
I think you could use the IsDigit function.
Something along these lines:
string textBoxText = "12kj3";
if (!textBoxText.Equals(String.Empty)) // this forces user to enter something
{
foreach (char c in textBoxText.ToArray())
{
if (!Char.IsDigit(c))
{
//return false;
}
}
//return true;
}
else
{
Console.WriteLine("Cannot be empty!");
}
Hope you get the idea.
You can use the following RegEx to check that it is a number "^\d+$" and required.
bool bV=false;
private void textBox1_Validated(object sender, EventArgs e)
{
TextBox textBoxText = sender as TextBox;
if (!textBoxText.Equals(String.Empty))
{
foreach (char c in textBoxText.Text.ToArray())
{
if (!Char.IsDigit(c))
{
if (!bV)
{
MessageBox.Show("Input value not valid plase Insert Integer Value");
bV = true;
textBox1.Text = String.Empty;
break;
}
}
}
}
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
bV = false;
}

Categories

Resources