Delete all non-digits from textbox - c#

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.

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 the last character when a key is pressed on a textbox C#

I'm trying to block the user press the same key (by example if the user have "asd" in a TextBox and the user press "x" the text box still contains "asd" but don't insert "x"), I have tried using KeyDown and KeyUp but it delete the last character but insterts the pressed ("asx" it deletes "d"). Sorry for my bad english.
private void txtInsert_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 104) //I'm trying to delete "h"
{
string cadena = txtInsert.Text;
cadena = cadena.Substring(0, cadena.Length - 1);
txtInsert.Text = cadena;
string cadena = "";
for (int i = 0; i < txtInsert.TextLength-1; i++)
{
cadena += txtInsert.Text[i];
}
txtInsert.Text = "";
txtInsert.Text = cadena;
}
}
Try KeyPress event (so we have char to operate with, not key which can be, say, left shift) and Handled in order to prevent user input (WinForms example):
private void myTextBox_KeyPress(object sender, KeyPressEventArgs e) {
TextBox box = sender as TextBox;
// Do nothing if
e.Handled =
e.KeyChar >= ' ' && // key is not control one (e.g. not backspace)
box.Text.Length >= 3; // Text Box Text has Length >= 3
}
If you want to prevent adding 'h'
// Do nothing on 'h' character
e.Handled = e.KeyChar == 'h';

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.

Getting integer from textbox

I want to write the event handler method button1_Click to calculate whether student’s Grade is “PASS” or “FAIL”. The student passes the course if the total score is greater than or equal to 50. The total score is Midterm(textbox1) + Final(textbox2) scores. However, teacher can give student Extra Credit(checkbox1) which is worth 10 points. The result will present in the textBox3
Here's my code:
private void button1_Click(object sender, EventArgs e)
{
int midtermInt = int.Parse(textBox1.Text);
int finalInt = int.Parse(textBox2.Text);
if (checkBox1.Checked)
{
if ((midtermInt + finalInt) + 10 >= 50)
{
grade.Text = "PASS";
}
else if ((midtermInt + finalInt) + 10 < 50)
{
grade.Text = "FAIL";
}
}
else if (!checkBox1.Checked)
{
if ((midtermInt + finalInt) >= 50)
{
grade.Text = "PASS";
}
else if ((midtermInt + finalInt) < 50)
{
grade.Text = "FAIL";
}
}
When I run it, it says "Inut string was not in a correct format.. :(
I'm very new to C# please advise me if my code is wrong anywhere
The input will only be integers never texts..
You should use int.TryParse insted int.Parse, it's check is specified string is in correct format.
You code may looks like this:
int midtermInt;
if (!int.TryParse(textBox1.Text, out midtermInt))
{
labelError.Text = "Icorrect value in field 'textBox1'".
return;
}
If you type non-numeric characters in your textbox and try to parse the text, it will throw you this exception. Try trimming the input and definitely consider adding UI validation to your forms.
You can add checking, if text in text box is in correct format in TextChanged event:
private void textBox_TextChanged(object sender, EventArgs e)
{
int val;
if (textBox.Text.Length == 0 || !int.TryParse(textBox.Text, out val))
tsPassingScore.Text = "0";
}
And in your click you can check if there is number in textBox again with int.TryParse
Also you can improve your code:
If final summ is not bigger then 50 - it is automatically smaller! And it would be more readable, if you introduce extra variable - for teachers extra credit:
int extraCredit = checkBox1.Checked ? 10 : 0;
int finalScore = midtermInt + finalInt + extraCredit;
if (finalScore >= 50)
grade.Text = "PASS";
else
grade.Text = "FAIL";

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