Asp.net TextBox can only enter numbers, backspaces, and decimal places (only one decimal point can be entered and cannot be the first one)
Asp tutorial. net textbox can only enter numbers, backspaces, and decimal places (only one decimal point can be entered and cannot be in the 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 the 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 2
If (e. keychar> = 48 & e. keychar <= 58) | e. keychar = 46 | e. keychar = 8)
{
// No selected text
If (this. textbox1.selectedtext. length = 0)
{
If (e. keychar = 46)
{
// Start 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;
}