I am using following code for validating textbox.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = SingleDecimal(sender, e.KeyChar);
}
public bool SingleDecimal(System.Object sender, char eChar)
{
string chkstr = "0123456789.";
if (chkstr.IndexOf(eChar) > -1 || eChar == Constants.vbBack)
{
if (eChar == ".")
{
if (((TextBox)sender).Text.IndexOf(eChar) > -1)
{
return true;
}
else
{
return false;
}
}
return false;
}
else
{
return true;
}
}
Problem is Constants.vbBack is showing error.If i didnt use Constants.vbBack,backspace is not workimg.What alteration can i make to work backspace.Can anybody help?
It is compulsory to have a dot ('. ') in a text for a decimal value. Minus is used as a decimal number and can be a signed number also. Sign decimal numbers, like -2.3, -0.3 can have minus sign at first position only.
Use JavaScript for validation input or use step=". 01" , which allows up to two decimal places on keypress input.
You can use Regular Expression to validate a Textbox to enter number only. In this case your Textbox accept only numbers. The following method also you can force your user to enter numeric value only. If you want to allow decimals add the following to the above code.
At this time, the Decimal data type can only be used within a Variant; that is, you cannot declare a variable to be of type Decimal. You can, however, create a Variant whose subtype is Decimal by using the CDec function.
here is the code I would use...
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
// allows 0-9, backspace, and decimal
if (((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46))
{
e.Handled = true;
return;
}
// checks to make sure only 1 decimal is allowed
if (e.KeyChar == 46)
{
if ((sender as TextBox).Text.IndexOf(e.KeyChar) != -1)
e.Handled = true;
}
}
You can make a method to check if it's a number.
Instead of checking for the .
as a decimal separator you should get it from CurrentCulture
object as it could be another character depending on where in the world you are.
public bool isNumber(char ch, string text)
{
bool res = true;
char decimalChar = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
//check if it´s a decimal separator and if doesn´t already have one in the text string
if (ch == decimalChar && text.IndexOf(decimalChar) != -1)
{
res = false;
return res;
}
//check if it´s a digit, decimal separator and backspace
if (!Char.IsDigit(ch) && ch != decimalChar && ch != (char)Keys.Back)
res = false;
return res;
}
Then you can call the method in the KeyPress
event of the TextBox
:
private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if(!isNumber(e.KeyChar,TextBox1.Text))
e.Handled=true;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With