asp.net textbox can only enter numbers, backspace, decimal point (only one decimal point and cannot be in first place)

Source: Internet
Author: User

ASP tutorial. NET textbox can only enter numbers, backspace, decimal point (only one decimal point and cannot be in first place)

private void Textbox1_keypress (object sender, KeyPressEventArgs e)
{
e.handled =! (Char.isnumber (E.keychar) | | | e.keychar = = (char) 8 | | | e.keychar = = '. ');
if (!e.handled) (sender as textbox). Tag = (sender as textbox). text;//Record last correct input
}

private void textBox1_TextChanged (object sender, EventArgs e)
{
if (!system.text.regularexpressions.regex.ismatch (sender as TextBox). Text, @ "^ (?!) 0d) d+ (. d*)? $ ")
{
int index = (sender as textbox). SelectionStart;
(Sender as TextBox). Text = (sender as textbox). Tag as String;
(Sender as TextBox). SelectionStart = index;
}
}

Method Two

if ((E.keychar >= && e.keychar <=) | | e.keychar = + | | e.keychar = 8)
{
No text selected
if (this.textbox1.selectedtext.length = 0)
{
if (E.keychar = 46)
{
Starting position
if (this.textbox1.text.length = 0)
{
E.handled = true;
}
Else
{
if (This.textbox1.text.indexof (".") > 0)
{
E.handled = true;
}
Else
{
e.handled = false;
}
}
}
Else
{
e.handled = false;
}
}
Select text
Else
{
if (E.keychar = 46)
{
String strchar = this.textbox1.text.substring (0, This.textbox1.selectionstart) + this.textbox1.text.substring ( This.textbox1.selectionstart + this.textbox1.selectionlength);
if (Strchar.indexof (".") > 0)
{
E.handled = true;
}
Else
{
e.handled = false;
}
}
}
}
Else
{
E.handled = true;
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.