Text box validation in c# - c#

I have a form with a text box that should only accept 4 digit year values between 1980-2011.
I'm sure there should be a simple c# validation control to implement this validation check, but I can't seem to find it.
Any suggestions?

Catch Validating event and add you validation code in there.
For a complete example check MSDN page.
For simple validation you can also use a MaskedTextBox.

First I'd say, use the max length property set to 4 so that no extra characters can be entered
Beyond that you would have to hook up your own controls to validate it (could be a on text changed validation, on lost focus, etc) that would check that only digits are entered and they are between your specified values

A MaskedTextBox would do the trick. Set the mask to your needs: msdn.
But I doubt it will check if the value is between a range. It probably only checks if the value is a integer.

Ok, I'm not going to write all the code here but here's what I'd do:
In textchanged event of your textbox;
Check if entered value is numeric
Check if it meets the pattern (compare chars with what you want)
For this one, you need to compare each number one by one. I'd suggest you to write a method which parses the text and compares them with your expected values. Something like this:
private bool IsNumberValid(string text)
{
String min = "1980",max=2011;
try
{
int minNumber = Convert.ToInt32(min.Substring(0,text.length));
int maxNumber = Convert.ToInt32(max.Substring(0,text.length));
int myNumber = Convert.ToInt32(text);
if(myNumber <= max && myNumber >= min)
return true;
}
catch(Exception ex)
{
return false; // number is not numeric
}
return false;
}
There may be small errors, didn't write it in VS. You'd need to check the length of the text and not call this method if it is 0.

Related

How can i solve "System.FormatException: 'Input string was not in a correct format.'" problem? [duplicate]

I added a textbox to my form and I'm trying to get the text from it but it comes up with an exception saying
"Input string was not in the correct format."
This is my code:
deleteQuestion = Convert.ToInt32(textBox6.Text);
addQuestion = Convert.ToInt32(textBox7.Text);
listOfQuestions.RemoveAt(deleteQuestion - 1);
foreach (RichTextBox box in boxForQuestions)
{
if (Convert.ToInt32(box.Tag) == deleteQuestion - 1)
{
boxForQuestions.Remove(box);
}
}
In the second part of the code my intention is to delete dynamically added rich text box.
Use Int32.TryParse if you are not in control of what your user types in those textboxes
int deleteQuestion;
if(!Int32.TryParse(textBox6.Text, out deleteQuestion))
{
MessageBox.Show("Not a valid number to delete a question!");
return;
}
int addQuestion;
if(!Int32.TryParse(textBox7.Text, out addQuestion))
{
MessageBox.Show("Not a valid number to add a question!");
return;
}
Of course, the same should be considered for the Tag property used inside the loop but this is set by your code so I presume that it is safe to consider it a valid integer
Another problem in your code is the remove inside the foreach loop. This cannot be done, you cannot change a collection while iterating over it. If you really need to remove an element from that collection you should consider to use a normal for... loop and looping from the last element towards the first one

How do I compare the elements in the array with the elements entered in the textbox sequentially in c#?

My goal is to actually make a guessing game, so I created two arrays with Mysql data called answers and questions. And what I want to do is take the value from the user and if it is true, for example my first answer 'fashion' matches the guess the user entered in the textbox, I want the label to write correct and continue with the next answer and try to find the next answer
My code returns true when I enter my values ​​in the array into the textbox, but I want them to be in order. How do you think I can use the for loop. How do you think I can use the for loop to make an ordered comparison?
for (int i=0;i<cevaplar.Count;i++)
{
string tahmin = textBox1.Text;
if(cevaplar.Contains(tahmin))
{
label1.Text = "true";
continue;
}
else
{
label1.Text = "false";
break;
}
}
}
In your code you use "cevaplar.Contains(tahmin)". With contains you're checking if tahim can be found anywhere in your array, without taking any order in account.
The solution to your problem should be quite simple. Just don't use contains in this situation but use a simple indexer to compare the elements. Try the following:
Replace:
if(cevaplar.Contains(tahmin))
{
...
}
With
if(cevaplar[i] == tahim) //here you check only if the i'th element is matching.
{
...
}
Good luck!

How to I condition a text box for a string if it holds a integer

I'm currently having some issues with error checking on a textbox. It holds a variable (called Price) as Double. Its purpose is to take a number in, and when a button is clicked it adds it to a running total displayed in a different textbox.
Now I have an error when checking if the textbox is empty using:
!string.IsNullOrWhiteSpace(txtAddItem.Text)
However, I'm unsure of how to error check if a string or character other than a number has been entered. Any ideas are appreciated.
Method 1: RegEx
You should try to use a regular expression. Regular expressions (Regex in short) are used to match strings against patterns. For example, if you only want to allow integers:
Regex r = new Regex(#"^[0-9]+$")
The Regex class has an .IsMatch(string s) method, where s is the string you want to test against the pattern.
Method 2: try-catch and Parse()
Another way to do it, which might be a bit more beginner-friendly, is a try-catch block. (I am assuming your TextBox's name is TextBox1 and you store the sum value in a runningSum variable.)
try {
double x = double.Parse(TextBox1.Text);
runningSum += x;
catch (ArgumentException ax) {
//handle if it is not a number in the TextBox
}
Method 3: TryParse()
A more advanced version which combines try-catch and Parse() is using the double.TryParse() method which returns a true/false value based on whether conversion was successful or not.
double x;
if (double.TryParse(TextBox1.Text, out x)) {
runningSum += x;
} else {
//handle if it is not a number in the TextBox.
}
If the value needs to be a valid double you could use 'double.TryParse'. Something like:
if (double.TryParse(txtAddItem.Text, out double price) == false)
{
// Show error or clear textbox
}
else
{
// Value is valid, add to total
}
You can use Double.TryParse()
double number;
if (Double.TryParse(txtAddItem.Text, out number)) {
Console.WriteLine("'{0}' is a valid double: {1}", value, number);
} else {
Console.WriteLine("Unable to parse '{0}' as a valid double", value);
}

How to leave textbox instead of send value to the database in windows forms using c#?

I developing a windows application so, I have only some textbox values send to
database remaining textbox values send 0 if the user does not enter any value.
I know how to send my approach is like that :
int x;
if(textbox1.Text!="")
{
x=int.Parse(textbox1.Text);
}
else
{
x=0;
}
Now I send a value to the database through my business logic something..
something.
This is my approach so I have a 35 textbox's in my project I want only 5
textbox's is required fields remaining are optional.
So is this correct approach to set values to 0 if the user doesn't enter any
value? otherwise give me your valuable suggestions.
Thanks.
So Is this correct approach to set values to 0 if the user doesn't enter any value?
Zero is a concrete, specific value. If you want to denote that the user did not use any value, use null.
An integer cannot store the value null, but a nullable integer can.
int? x = null;
Note that your database column must allow nulls for this to work.
Note that int.Parse() can throw an exception (if the input is not a number, e.g. Hello). It is better to use int.TryParse like this
int tmp;
bool valid = int.TryParse(textbox1.Text, out tmp);
x = valid ? (int?)tmp : null; // Assumes x is a nullable integer.
You could perhaps use the Int32.TryParse Method:
Int32.TryParse(textbox1.Text, out x);
However, if no value is provided, it may be better to use null values instead to your database.
Hope this helps!
Write the validation for all the 5 textboxes which are required. and for optional ones after the 5 textbox validation.
void AddZerotoText(Control con)
{
foreach (Control c in con.Controls)
{
if (c is TextBox)
{
if(((TextBox)c).Text == "")
((TextBox)c).Text = "0";
}
}
}
So this will check the validation for first 5 textboxes which are required and then check for all the textboxes which are blank and will add 0 in the textbox.

Textbox Contains Only Certain Characters C#

I have a simple WinForms app that generates random numbers based on the maximum number entered. For the maximum number text box I already have code that checks the 'key press' input so that numbers and "." are the only characters input. Hence, decimal numbers are allowed. However, I also want to check that the text box doesn't just contain 0's and "." An outline of my code is shown below:
if(txbInput.Text.Length == 0)
{
validation fails
}
else if(txbInput Contains just 0s and .)
{
validation also fails
}
else{
do maths
}
What would be the correct way to do this in the 'else if' statement?
Why don't you use Decimal.TryParse or Double.TryParse instead?
decimal d;
if(!decimal.TryParse(txbInput.Text, out d))
{
// validation fails, output an appropriate message to the user
}
else if (d == 0m)
{
// validation fails, output an appropriate message to the user
}
Try to use a NumericUpDown control instead of TextBox. This will eliminate validation and parsing in your code, except for comparing its Value property with zero.
Remark: To use this control for editing a real numbers, set an appropriate values for the properties DecimalPlaces and Increment.
you could use the KeyPressEvent for that...
like
private void tb1_KeyPressed(object o,KeyPressEvents e)
{
if(/*insert your validation here*/)
{//valid case
e.Handled=false;
}
else
{//false case
e.Handled=true;
//inform user about mistake
}
}
if you set Handled =true then nothing will happen after a key got pressed. Through that you can surpress keys in a textbox

Categories

Resources