How to validate for numbers without using keypress option
why isnt Char.IsNumber
or .IsDigit
working
or should I use regex expression for validation
private bool ValidateContact()
{
if (Char.IsNumber(textBox4.Text)){
return true;
}
How to validate for numbers without using keypress option
why isnt Char.IsNumber
or .IsDigit
working
or should I use regex expression for validation
private bool ValidateContact()
{
if (Char.IsNumber(textBox4.Text)){
return true;
}
You could simply parse the number:
private bool ValidateContact()
{
int val;
if (int.TryParse(textBox4.Text, out val))
{
return true;
}
else
{
return false;
}
}
You are trying to call a method that is written for char
for string
. You have to do them all separately, or use a method that is much easier to use, like the above code.
why isnt Char.IsNumber or .IsDigit working
because Char.IsDigit
wants a char
not a string
. So you could check all characters:
private bool ValidateContact()
{
return textBox4.Text.All(Char.IsDigit);
}
or - better because IsDigit
includes unicode characters - use int.TryParse
:
private bool ValidateContact()
{
int i;
return int.TryParse(textBox4.Text, out i);
}
Parse the string as:
private bool ValidateContact()
{
int n;
return int.TryParse(textbox4.Text, out n);
}
as documented here http://codepoint.wordpress.com/2011/07/18/numeric-only-text-box-in-net-winforms/ :-
We can create Numeric only text boxes in .Net Windows forms application with adding below code in Key Press Event.
Numeric only text boxes
private void txtBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}
You should be using
int n;
bool isNumeric = int.TryParse("123", out n);
Not Char.IsNumber()
as that only tests a character.
Try supress every key but numeric or decimal point on textbox.KeyPress
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}
Why controlling on keypress ?
Because alerting user after he enters a value is not a efficent way to get input from user. Instead of doing this , you can prevent user from entering non/valid values when user typing.
Based on Matt Hamilton's Ansver on this Question
You can use regular expression too.
if (System.Text.RegularExpressions.Regex.IsMatch("[^0-9]", textBox1.Text))
{
MessageBox.Show("Please enter only numbers.");
textBox1.Text.Remove(textBox1.Text.Length - 1);
}
Also you can check, textbox only allow numeric value :