开发者

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

  1. Check client side via ajax/javascript to be sure only one decimal is entered, and

  2. You can reuse the extender on other textboxes on future forms.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜