Validating a textBox in simple calculator to only accept a number - c#

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
}

Related

TextBox only allow enter certain range of numbers, but its not accept some correct value

Good evening,
trying to make WPF textbox accept only double value between 3 and 2813
in the code below ,I can't write any value start with 1 or 2
like 11,22,113,215,2008
private bool IsValid(string str)
{
double i;
return double.TryParse(str, out i) && i >= 3 && i <= 2813;
}
private void L_Text_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = !IsValid(((TextBox)sender).Text + e.Text);
}
PreviewTextInput occurs whenever the user presses a key. So we can't know whether the user intends to write "2" or "22" at this moment.
To evaluate the value we must be sure that the user finished writing. You can use LostFocus event for this purpose.
private bool IsValid(string str)
{
double i;
return double.TryParse(str, out i) && i >= 3 && i <= 2813;
}
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
var txt = sender as TextBox;
if (!IsValid((txt.Text)))
{
//invalid delete text
txt.Text = "";
}
}
Detailed validation: https://stackoverflow.com/a/37255232/1431001
There are 2 things you could do
You could evaluate if it starts with a specific character, and then parse that
You could use https://help.syncfusion.com/wpf/double-textbox/getting-started

Delete all non-digits from textbox

I have textbox1 where i enter number. Example: 123
I also have textbox2 where the sum is shown. Example: 6 (1+2+3)
What i need is. If there is only numbers in my textbox1, then everything is fine and i'm getting sum.
If there is something more than numbers like 1a2b3c i want the programm to show message box with Warning and a text. Delete all non-digits? If the guy press Yes, then it does delete abc and only 123 is left. If no, then Error shows up.
My code:
private void button1_Click(object sender, EventArgs e)
{
int cipari = Convert.ToInt32(textBox1.Text);
int summa = 0;
for (int n = cipari; n > 0; summa += n % 10, n /= 10) ;
DialogResult dialogResult = MessageBox.Show("Delete all non-digits?", "Warning", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
textBox2.Text = summa.ToString();
}
else if (dialogResult == DialogResult.No)
{
textBox2.Text = "Error! You can't sum non-digits!";
}
}
Simply check for the prescence of non-digit characters:
foreach(Char c in textBox1.Text) {
if( !Char.IsDigit( c ) ) {
MessageBox.Show("Non-digits detected");
return;
}
}
if you only want numbers then you can use a small function the scrub and warn the user on the textchanged event of each effected text box. This will show a warning to the user and then remove the invalid character.
private void validateText(TextBox tb)
{
if (System.Text.RegularExpressions.Regex.IsMatch(tb.Text, #"[^0-9]"))
{
MessageBox.Show("Please enter only numbers.");
tb.Text = tb.Text.Remove(tb.Text.Length - 1);
tb.Refresh();
tb.SelectionStart = tb.Text.Length;
tb.SelectionLength = 0;
}
}
use:
private void textbox1_TextChanged(object sender, EventArgs e)
{
validateText(textbox1);
}
That's an odd program flow honestly. But you can do it like:
if(!textBox2.Text.All(char.IsDigit)
{
DialogResult dialogResult = MessageBox.Show("Delete all non-digits?", "Warning", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
textBox2.Text = string.Concat(textBox2.Text.Where(char.IsDigit));
}
else if (dialogResult == DialogResult.No)
{
textBox2.Text = "Error! You can't sum non-digits!";
}
}
Why to delete numbers every time user enters alphabets, I guess the best practice is to never let the user enter anything else than a number.
First create a function that checks if the text entered is integer or not
like this :
private bool IsNumber(string text)
{
Regex regex = new Regex("[^0-9.-]+"); //regex that matches if the text contains only numbers
return regex.IsMatch(text);
}
Then Use the textbox's PreviewTextInput event to stop the user from entering nothing but integers (decimal and -) too.
private void Button_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = IsNumber(e.Text);
}
It's important to set the e.handled to the IsNumber function as here only it checks using this method if the input string is acceptable or not and prevents the user from entering it.

How do to add validation to my calculator in 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.

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

Why my form is getting closed when i move the Tab to and fro from the textbox

I have the following code in my TextBox leave event:
private void txtAmount_Leave(object sender, EventArgs e)
{
int x = Convert.ToInt32(txtAmount.Text);
double res = (double)x / 100;
txtAmount.Text = "$" + res.ToString();
}
But if move back to the previous control by hitting Shift+Tab and again moving back to the same textbox and then trying to move to other the form is getting closed automatically. Why does this happen?
The call to Convert.ToInt32() is probably throwing an exception, likely due to being unable to convert the string in your TextBox to an integer. Convert.ToInt32() can throw the following exceptions (descriptions from MSDN):
FormatException - value does not consist of an optional sign followed by a sequence of digits (0 through 9).
OverflowException - value represents a number that is less than Int32.MinValue or greater than Int32.MaxValue.
It's likely a FormatException, thrown when you leave the TextBox after the $ is prepended to your string, or after you enter any non-numeric characters (letters, etc). To fix this, you have a couple of options:
Add a try / catch block around your code to handle any exceptions.
Use Int32.TryParse() instead of Convert.ToInt32().
Add some code that will prevent non-numeric characters from being entered in your TextBox
Here's an improved version of your event handler:
private void txtAmount_Leave(object sender, EventArgs e)
{
string toParse = txtAmount.Text.TrimStart('$');
int parsed;
if (Int32.TryParse(toParse, out parsed))
{
double res = (double)parsed / 100;
txtAmount.Text = "$" + res.ToString();
}
}
The first time you leave this textbox, its contents will be changed to "$123" (for example). The second time you leave, trying to convert that to int will throw an exception.
You could use the overload of TryParse that takes a NumberStyle, something like this, assuming your goal is to just show a currency value with no decimal places.
double number;
if (double.TryParse(txtAmount.Text, NumberStyles.Currency, CultureInfo.CurrentUICulture, out number))
{
txtAmount.Text = number.ToString("C0");
}
else
{
MessageBox.Show("Could not convert.");
}
After reading #Donut's comment on his answer, I am not sure what your goal is. If you'd like to truncate the cents off but still show the ".00", you can do this:
txtAmount.Text = ((int)number).ToString("C");
Or do this, which will round:
txtAmount.Text = (Convert.ToInt32(number)).ToString("C");
If this does not help, please clarify and let us know what you are trying to accomplish.
Try this:
private void txtAmount_Leave(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(txtAmount.Text) && txtAmount.Text.StartsWith("$"))
txtAmount.Text = txtAmount.Text.Substring(1);
int x = Convert.ToInt32(txtAmount.Text);
double res = (double)x / 100;
txtAmount.Text = "$" + res.ToString();
}
Check the txtAmount.Text for the $ sign, before trying to convert it to an int. If the $ sign is present, strip it out, and convert the rest of the input to an int.
Also, you might want to use the Int32.TryParse method, as that will help you figuring out whether the entered text can be converted into an int or not.
You may want to change your code to remove the $ before working with the number:
private void txtAmount_Leave(object sender, EventArgs e)
{
int x = 0;
int.TryParse(txtAmount.Text.Replace("$", string.Empty), out x);
double res = (double)x / 100;
txtAmount.Text = "$" + res.ToString();
}
I got the solution
private void txtAmount_Leave(object sender, EventArgs e)
{
string strAmnt = string.Empty;
strAmnt = txtAmount.Text;
if (strAmnt.Contains(".") && !strAmnt.Contains("$"))
{
txtAmount.Text = "$" + strAmnt;
while (txtAmount.Text.Length - txtAmount.Text.IndexOf(".") <= 2)
{
txtAmount.Text += "0";
}
}
else
if (strAmnt.Contains("$") && !strAmnt.Contains("."))
{
Int64 amnt = 0;
strAmnt = strAmnt.Replace("$", "");
try
{
amnt = Convert.ToInt64(strAmnt);
double amt = (double)amnt / 100;
txtAmount.Text = "$" + amt.ToString();
}
catch (FormatException ie)
{
MessageBox.Show("Invalid Format");
}
}
else
if (!strAmnt.Contains(".") && !strAmnt.Contains("$"))
{
try
{
int x = Convert.ToInt32(txtAmount.Text);
double res = (double)x / 100;
txtAmount.Text = "$" + res.ToString();
while (txtAmount.Text.Length - txtAmount.Text.IndexOf(".") <= 2)
{
txtAmount.Text += "0";
}
}
catch (FormatException ie)
{
MessageBox.Show("InvalidFormat");
}
}
while (txtAmount.Text.Length - txtAmount.Text.IndexOf(".") <= 2)
{
txtAmount.Text += "0";
}
}

Categories