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
Related
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
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);
}
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.
Im simulating a vending machine and would like to set the product quantity text box to only accept values greater than 0. when i enter -1 my program accepts this value and displays it which i dont want.can someone help please
code is:
//create a new Employee object
try // Exception handling to ensure that incorrect data type cannot be entered into text box creating a new product
{
Products newProd = new Products(this.textProdID.Text);
newProd.ProductName= this.textProdName.Text;
newProd.ProductQuantity= Convert.ToInt32(this.textProdQuantity.Text);
newProd.ProductPrice= Convert.ToDouble(this.textProdPrice.Text);
ProductList.Add(newProd);
MessageBox.Show(newProd.ProdName + " has been added to the product list");
}
catch
{
MessageBox.Show("Format entered into text box Is incorrect please check and try again");
}
You should add the Quantity range validation as per your specification - see the code snippet shown below:
//create a new Employee object
try // Exception handling to ensure that incorrect data type cannot be entered into text box creating a new product
{
Products newProd = new Products(this.textProdID.Text);
newProd.ProductName= this.textProdName.Text;
newProd.ProductQuantity= Convert.ToInt32(this.textProdQuantity.Text);
// add the input range validation
if (newProd.ProductQuantity<=0) throw new ArgumentException ("Quantity must be a positive number.");
newProd.ProductPrice= Convert.ToDouble(this.textProdPrice.Text);
ProductList.Add(newProd);
MessageBox.Show(newProd.ProdName + " has been added to the product list");
}
catch
{
MessageBox.Show("Format entered into text box Is incorrect please check and try again");
}
Another solution is just to show a MessageBox with error message if validation fail and return. Further performance optimization can be achieved by using TryParse() instead of Convert method, but considering relatively simple task, both solutions pertinent to this case will suffice the purpose. As a general recommendation, consider adding the input validation to the Control event (e.g. TextBox.TextChanged +=(s,e)=>{ // validation};
Also, pertinent to your case, consider setting the object to null in validation fail.
Hope this will help. Best regards,
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.