How do to add validation to my calculator in c# - c#

I'm creating a calculator and I want to add validation code in it, so that if anything besides numbers is entered, an error message appears.
private void button4_Click(object sender, EventArgs e)
{
int R = Convert.ToInt32(textBox1.Text);
int I = Convert.ToInt32(textBox2.Text);
int number2;
if (int.TryParse(textBox1.Text, out number2))
{
int E = R - I;
textBox3.Text = E.ToString();
}
else
{
textBox2.Text = ("value entered is not whole number");
}
}
This is the code I am trying to use but it comes up with an error message when I enter a non-numeric value.

You are calling Convert.ToInt32 method before TryParse and that causes the exception. Don't do that, do the validation with TryParse.
private void button4_Click(object sender, EventArgs e)
{
int R, I;
if (int.TryParse(textBox1.Text, out R) &&
int.TryParse(textBox2.Text, out I))
{
int E = R - I;
textBox3.Text = E.ToString();
}
else
{
MessageBox.Show("You have entered an invalid value!");
}
}
Also you might consider using more descriptive variable names instead of E, R, I...

private void button4_Click(object sender, EventArgs e)
{
int R, I;
if (int.TryParse(textBox1.Text, out R)
&& int.TryParse(textBox2.Text, out I))
{
int E = R - I;
textBox3.Text = E.ToString();
}
else { textBox3.Text = ("value entered is not whole number"); }
}

Make sure you try to parse the strings into ints with TryParse always, rather than just converting immediately... if there are letters, the conversion fails.
private void button4_Click(object sender, EventArgs e)
{
int number1;
int number2;
if (int.TryParse(textBox1.Text, out number1) && int.TryParse(textBox2.Text, out number2))
{
//do your thang (subtraction, assigning the result to TextBox3)
//return
}
else
{
MessageBox.Show("Oh no you entered something that's not an int!");
}
}
I might also add that making the value of one of your input text boxes "Value entered is not a whole number" is kind of a weird UI experience. I'd mark the textbox in red or pop up a message box or something instead, leaving the entered value in the box, in case it was some really long number like 879320!78 where they accidentally entered a weird symbol or something.

Related

Program chrases after deleting the int value from a textbox

I'm working on a project in Visual Studios 2015 (Visual c#).
I have a textbox in which is introduced a number beetween 0 and 11.So if the number isn't beetween 0 and 11 or in the textbox1 is introduced a char or string value, a Message Box will pop up saying that the value introduced it's incorrect.
But , if I delete the numbers from the textbox1 or introduce a char character ,press space - the application chrases.
Here is the code :
private void textBox1_TextChanged(object sender, EventArgs e)
{
int a;
a = Convert.ToInt32(textBox1.Text);
if (textBox1.Text == null)
{
MessageBox.Show("incorrect");
}
else
if (a < 0 || a > 11)
{
MessageBox.Show("incorrect");
}
}
I need to find a method that doesn't crashes when I introduce a char or string value ,or a number that isn't between 0 and 11.
(the numbers introduced in the textbox1 are always int)
Your app crashes because you are trying to convert TextBox.Text value to int and it is possible that this value cannot be converted to int so, you get exception. If this value is non-number or empty string then Convert.ToInt32() crashes (throws exception and this exception in not handled - crash).
In your case it will be better to use int.TryParse() method instead of Convert.ToInt32() - if int.TryParse() returns true then it is number and you can check if value is in needed range, if int.TryParse() returns false then value cannot be parsed to int(it is some non-digit string):
private void textBox1_TextChanged(object sender, EventArgs e)
{
int a;
bool parsed = int.TryParse(textBox1.Text, out a);
if (!parsed || a < 0 || a > 11)
{
MessageBox.Show("incorrect");
}
}
Try This
private void textBox1_TextChanged(object sender, EventArgs e)
{
int a;
int = 0;
try
{
a = Convert.ToInt32(textBox1.Text);
}
catch(Exception exc){
MessageBox.Show("incorrect exception thrown");
}
if (textBox1.Text == null)
{
MessageBox.Show("incorrect");
}
else
if (a < 0 || a > 11)
{
MessageBox.Show("incorrect");
}
}
The try parse equivelant:
private void textBox1_TextChanged(object sender, EventArgs e)
{
int a;
bool succes = int.TryParse(textBox1.Text, out a);
if(!succes)
{
MessageBox.Show("incorrect");
return;
}
if (a < 0 || a > 11)
{
MessageBox.Show("incorrect");
}
// ... Do stuff to a?
}
Your conversion is not correct
private void textBox1_TextChanged(object sender, EventArgs e)
{
int a;
bool result= int.TryParse(textBox1.Text, out a);
if (textBox1.Text == null || res)
{
MessageBox.Show("incorrect");
}
else
if (a < 0 || a > 11)
{
MessageBox.Show("incorrect");
}
}

I keep getting" Input string was not in a correct format." error when adding values textboxes

I have been through several posts of the same error, and I cant figure it out why it wont work for me.
I am trying to add multiple values in textboxes. Im starting with 2 textboxes to test, but my plan is to have a total of 10. But i keep getting this error. I have this event on each textbox. Ideas? IF needed, i can include my asp code.
protected void calculateLabs(object sender, EventArgs e)
{
string lab01 = TextBox1.Text;
string lab02 = TextBox2.Text;
int num1 = int.Parse(lab01);
int num2 = int.Parse(lab02);
int final = num1 + num2;
Label1.Text = final.ToString();
}
UPDATE, it works, but the exception still displays the message on the label, once i input the next values, the error goes away.
protected void calculateLabs(object sender, EventArgs e)
{
try
{
int num1 = Convert.ToInt32(TextBox1.Text);
int num2 = Convert.ToInt32(TextBox2.Text);
int final = num1 + num2;
Label1.Text = final.ToString();
}
catch(Exception ex)
{
Label1.Text = ex.Message;
}
}
Why are you using the word final as a variable name? It is a reserved word for c# and other languages try using other variable names like total, finalNum, etc., instead.
Not sure why, i keep getting the error. So i just included where the default value of each textbox is 0.
<asp:TextBox ID="part1" runat="server" AutoPostBack="true" OnTextChanged="calculateSum" Text="0">
Doesnt error out anymore.
Make sure the entered strings in both Textboxes are numbers.
Refer to this question to do so:
How do I make a textbox that only accepts numbers?
Try Convert.ToInt32(string s) instead of Int.Parse(string s)
Add a try-catch block and tell us where exactly is the exception thrown.
UPDATE:
Before converting values of Textbox1 & Textbox2 make sure they have values and not euqual null
protected void calculateLabs(object sender, EventArgs e)
{
try
{
if (!string.IsNullOrEmpty(TextBox1.Text) && !string.IsNullOrEmpty(TextBox2.Text))
{
int num1 = Convert.ToInt32(TextBox1.Text);
int num2 = Convert.ToInt32(TextBox2.Text);
int final = num1 + num2;
Label1.Text = final.ToString();
}
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
}

Input string was not in a correct format in double.Parse

I am new to C#. I'm trying to make a calculator, but the following error occurred:
Input string was not in a correct format.
This is the summary of the code:
double num1, num2, result;
private void button14_Click(object sender, EventArgs e)
{
num1 = Convert.ToDouble(textBox1.Text);
textBox1.Text = String.Empty;
num2 = double.Parse(textBox1.Text); **//ERROR OCCURED HERE**
result = num1 - num2;
}
private void button13_Click(object sender, EventArgs e)
{
num1 = Convert.ToDouble(textBox1.Text);
textBox1.Text = String.Empty;
num2 = System.Double.Parse(textBox1.Text); **//ERROR OCCURED HERE**
result = num1 + num2;
}
How to convert string to a double type?
Also remember that the Parse method is relying on the culture of your operating system to perform the conversion, so try to change your code to
num2 = double.Parse(textBox1.Text, CultureInfo.InvariantCulture);
You might also consider to use the
double.TryParse
method for better exception handling.
What are you trying to achieve with this code? It seems that your algorythm is wrong.
Like others said, this code
textBox1.Text = String.Empty;
num2 = double.Parse(textBox1.Text);
will throw an Exception because an empty string cannot be converted to Double!
So, I'm wondering why did you reset your field. I thought about it for a while, and maybe I got what are you trying to do. Let's say you type a number in TextBox1. Then you press the "-" button to subtract and then you want to enter the second number to view the result. Is this the case? If it is, the code you wrote is not going to wait for your next input!
In fact, when you click the button, it just executes all the lines you wrote. I'd write something like this instead.
double num1, num2, result;
string operation;
private void button14_Click(object sender, EventArgs e) //Minus Button
{
if (textBox1.Text != String.Empty) //Added if statement to see if the textBox is empty
num1 = Convert.ToDouble(textBox1.Text);
else
num1 = 0; //If textBox is empty, set num1 to 0
textBox1.Text = String.Empty;
operation = "-";
}
private void button13_Click(object sender, EventArgs e) //Equals Button
{
if (textBox1.Text != String.Empty)
num2 = Convert.ToDouble(textBox1.Text);
else
num2 = 0;
if (operation == "-")
{
result = num1 - num2;
textBox1.Text = Convert.ToString(result);
}
if (operation == "+")
{
//You got it
}
//And so on...
}
EDIT: If the string is empty, this is going to always throw Exceptions, so I added a control. If the string is empty, value becomes zero.
Since you have cleared the textbox on the previous line, the Parse conversion fails.
textBox1.Text = String.Empty;
num2 = double.Parse(textBox1.Text);
How will it convert String.Empty to Double?
The way of doing it is not right.
For example, if the "+" button is clicked, you have to check whether there was already a number. If so,, add the numbers and display the result:
Double num;
private void Add_Click(object sender, EventArgs e)
{
If (num != null)
{
num == num + Convert.ToDouble(textBox1.Text);
}
else
{
num1 == Convert.ToDouble(textBox1.Text);
}
textBox1.Text = num;
}
Seems like num2 value should be fetched from textbox2 not textbox1(You are setting textbox1.text to empty and trying to parse it to double again)
//You are setting textbox1 to empty
textBox1.Text = String.Empty;
//here trying to parse it to double
num2 = double.Parse(textBox1.Text);
Also don't use Convert.ToDouble(textBox1.Text) directly. if users type non numeric values your code will crash. first check if its a valid number, always use doube.TryPrase()
double num1;
double.TryParse(textBox1.Text, out num1);
Your code seems hard to understand whats the use of button_13 and button_14;
I will assume your trying to do this:
bool ifNew = true;
double num1 ,num2,result;
private void Add_Click(object sender, EventArgs e))
{
if(ifNew)
{
num1 = Convert.ToDouble(textBox1.Text);
textbox1.Clear();
ifNew = false;
result += num1;
}
else
{
num2 = Convert.ToDouble(textBox1.Text);
textbox1.Clear();
result += num2;
num1 = 0D;
num2 = 0D;
ifNew = true;
}
}
private void Equals_Click(object sender, EventArgs e)
{
textboxl.Text = string.Format("{0:N}",result);
}
Or you could use Double.Parse in my Convert.ToDouble
It depends on your operation but I am visualizing
how to do add operation you can change and edit this
depends on your operation

Increment the number by 1

I would like to see label6 display the number of correct times the user chooses the number. And label7 display the number of times the user choose incorrectly. Its not incrementing by one.
Error 1 Operator '++' cannot be applied to operand of type 'string'
Error 2 Operator '++' cannot be applied to operand of type 'string'
private void button1_Click(object sender, EventArgs e)
{
string correct="0";
string incorrect="0";
RandomNumber(0,99);
button2.Enabled = true ;
button1.Enabled = false;
label3.Visible = true;
if (textBox1.Text == label1.Text)
label3.Text=("Winner");
label6.Text = correct +1;
if (textBox1.Text != label1.Text)
label7.Text = incorrect= +1;
label3.Text=(string.Format("Sorry - You Lose, The number is {0}", label1.Text));
}
Edit (From OP's answer to his own question):
I have tried the ways your suggesting but the number doesnt increase by one everytime I guess wrong.
private void button1_Click(object sender, EventArgs e)
{
int correct=0;
int incorrect=0;
RandomNumber(0,99);
button2.Enabled = true ;
button1.Enabled = false;
label3.Visible = true;
if (textBox1.Text == label1.Text)
{
label3.Text = ("Winner");
label6.Text = (++correct).ToString();
}
else if (textBox1.Text != label1.Text)
{
label7.Text = (incorrect+1).ToString();
label3.Text = (string.Format("Sorry - You Lose, The number is {0}", label1.Text));
}
}
It doesn't look like you're persisting the correct and incorrect
Create Properties:
public int Correct { get; set; }
public int Incorrect { get; set;}
Then:
private void button1_Click(object sender, EventArgs e)
{
RandomNumber(0,99);
button2.Enabled = true ;
button1.Enabled = false;
label3.Visible = true;
if (textBox1.Text == label1.Text)
{
label3.Text=("Winner");
label6.Text = (++this.Correct).ToString();
}
else
{
label3.Text=(string.Format("Sorry - You Lose, The number is {0}", label1.Text));
label7.Text = (++this.Incorrect).ToString();
}
}
You are storing your correct and incorrect variables as string.
Use int instead like this:
int correct = 0;
int incorrect = 0;
and change your code to:
correct++;
label6.Text = correct.ToString();
and:
incorrect++;
label7.Text = incorrect.ToString();
Adding to strings, correct and incorrect will just append the string representation of what's added. You have to convert it to an integer type, then increment, then convert back to string. However it would be easier to just keep these variables as integer instance variables. That way incrementing is trivial and you are actually keeping the correct count and not resetting every time the button gets clicked. (There are actually a number of problems with the code)
// instance variables
private int correct = 0;
private int incorrect = 0;
private void button1_Click(object sender, EventArgs e)
{
RandomNumber(0,99);
button2.Enabled = true ;
button1.Enabled = false;
label3.Visible = true;
if (textBox1.Text == label1.Text)
{
label3.Text=("Winner");
label6.Text = (++correct).ToString(); // convert int to string
}
// indentation does not indicate the block
else //if (textBox1.Text != label1.Text)
{
label3.Text=(string.Format("Sorry - You Lose, The number is {0}", label1.Text));
label7.Text = (++incorrect).ToString();
}
}
Or you can use:
correct = correct + 1; ( I think this is what you were trying to achieve)
incorrect = incorrect + 1;
OR
correct += 1;
incorect += 1;
label6.Text = correct +1;
only sets label6's value to correct + 1; it does not change the value of correct. If you use:
int correct;
label6.Text = (++correct).ToString();
you should see what you want.

Validating a textBox in simple calculator to only accept a number

I am building a simple calculator( add + Multiply two numbers) using Windows Form Application
the code is working now but its when i try to validate it.
private void txtBtn1_Click(object sender, EventArgs e)
{
double a, b, c; // Declearing Variables
a = double.Parse(txtBox1.Text);
b = double.Parse(txtBox2.Text);
c = a + b;
txtLbl.Text = c.ToString();
}
I have tried this check:
if (int.TryParse(txtBox.Text, out int tempNum1) == false)
return;
and somthing like this:
if ((int.TryParse(txtBox1.Text, out int num1) == false) &&
(int.TryParse(txtBox1.Text, out int num2) == false))
MessageBox.Show("Please Enter a Number");
return;
Yes, you should use TryParse, e.g.
private void txtBtn1_Click(object sender, EventArgs e)
{
if (double.TryParse(txtBox1.Text, out double a) &&
double.TryParse(txtBox2.Text, out double b))
txtLbl.Text = (a + b).ToString(); // if both TextBoxes have valid values
else {
// At least one TextBox has invalid Text
txtLbl.Text = "???";
}
}
If you want to help user in error correction we can name the invalid argument and put a keyboard focus on it:
private void txtBtn1_Click(object sender, EventArgs e) {
if (double.TryParse(txtBox1.Text, out double a)) {
if (double.TryParse(txtBox2.Text, out double b))
txtLbl.Text = (a + b).ToString();
else {
if (txtBox2.CanFocus)
txtBox2.Focus();
MessageBox("Mot a Valid 'B' Number");
}
}
else {
if (txtBox1.CanFocus)
txtBox1.Focus();
MessageBox("Mot a Valid 'A' Number");
}
}
An alternative to avoid doing any manual validation is to swap your text box for a NumericUpDown component, it does all the validation for you and works the same as a textbox.
Or you could use regex.
string compare = "1234";
Regex regex = new Regex(#"^\d$");
if (regex.IsMatch(compare))
{
//It is only numbers
}

Categories