【www.gdgbn.com--安卓教程】

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;
  }

本文来源:http://www.gdgbn.com/shoujikaifa/25700/