Prevent zero in text box
5 answers
How you plan to do this is very annoying to the user. You can guess what the user wants to enter and act on your guess, but you can be wrong.
It also has holes, for example the user can enter "10" and then delete "1". Or he can insert "0" - you will allow insertion, right?
So my solution would be: let him enter any digit he likes, in whatever way he likes, and only validate the input after he's finished, like when the input loses focus.
+8
a source to share
Use int.TryParse to convert the text to a number and check if it is not 0. Use the Validating event to check.
// this goes to you init routine
textBox1.Validating += textBox1_Validating;
// the validation method
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (textBox1.Text.Length > 0)
{
int result;
if (int.TryParse(textBox1.Text, out result))
{
// number is 0?
e.Cancel = result == 0;
}
else
{
// not a number at all
e.Cancel = true;
}
}
}
EDIT:
Ok, since you are using WPF you should take a look at how to implement WPF path validation . Here is a validation class that implements the above logic:
public class StringNotZeroRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (textBox1.Text.Length == 0)
return new ValidationResult(true, null);
int result;
if (int.TryParse(textBox1.Text, out result))
{
// number is 0?
if (result == 0)
{
return new ValidationResult(false, "0 is not allowed");
}
}
else
{
// not a number at all
return new ValidationResult(false, "not a number");
}
return new ValidationResult(true, null);
}
}
+3
a source to share
This is another variation on the theme:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
char newChar = Convert.ToChar(e.KeyValue);
if (char.IsControl(newChar))
{
return;
}
int value;
e.SuppressKeyPress = int.TryParse((sender as TextBox).Text + newChar.ToString(), out value) ? value == 0 : true;
}
+1
a source to share