asp教程.net textbox只能輸入數字、退格、小數點(小數點只能有一個且不能在第一位)
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;//記錄最後一次正確輸入
}
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;
}
}
//方法二
if ((e.keychar >= 48 && e.keychar <= 58) || e.keychar == 46 || e.keychar == 8)
{
//無選擇文字
if (this.textbox1.selectedtext.length == 0)
{
if (e.keychar == 46)
{
//起始位置
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;
}
}
//選擇文字
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;
}