How to restrict the TextBox to accept only one dot in decimal number in keypress event in C#
I am developing a windo开发者_开发技巧ws mobile application, in this i want to restrict the asp.net textbox to accept only one dot in decimal number (C#) so please suggest me how to do this.
Thanks in advance.
I would just register to the Textbox TextChanged event. To validate a decimal number, you could either use a basic regex or Decimal.TryParse method. Both methods are shown below.
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
if(!Regex.IsMatch(TextBox1.Text, @"[0-9]+(\.[0-9][0-9]?)?"))
TextBox1.BackColor = Color.Red;
decimal value;
if(!decimal.TryParse(TextBox1.Text, out value))
TextBox1.BackColor = Color.Red;
}
One way to do it is with control extenders. You can
Check client side via ajax/javascript to be sure only one decimal is entered, and
You can reuse the extender on other textboxes on future forms.
精彩评论