textbox中只允许输入数字和小数点

把Textbox的KeyPress事件设置为如下方法,就可以实现限制输入

///


/// 只能输入数字(含负号小数点)
///

///
///
public static void OnlyEnterNumber(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 13 && e.KeyChar != 45 && e.KeyChar != 46)
{
e.Handled
= true;
}

//输入为负号时,只能输入一次且只能输入一次
if (e.KeyChar == 45 && (((TextBox)sender).SelectionStart != 0 || ((TextBox)sender).Text.IndexOf("-") >= 0)) e.Handled = true;
if (e.KeyChar == 46 && ((TextBox)sender).Text.IndexOf(".") >= 0) e.Handled = true;
}


///
/// 只能输入正实数
///

///
///
public static void OnlyEnterPlusNumber(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 13 && e.KeyChar != 46)
{
e.Handled
= true;
}
if (e.KeyChar == 46 && ((TextBox)sender).Text.IndexOf(".") >= 0) e.Handled = true;
}


///
/// 只能输入整数
///

///
///
public static void OnlyEnterInt(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 13 && e.KeyChar != 45)
{
e.Handled
= true;
}

//输入为负号时,只能输入一次且只能输入一次
if (e.KeyChar == 45 && (((TextBox)sender).SelectionStart != 0 || ((TextBox)sender).Text.IndexOf("-") >= 0)) e.Handled = true;
}

///
/// 只能输入正整数
///

///
///
public static void OnlyEnterPlusInt(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 13)
{
e.Handled
= true;
}
}

你可能感兴趣的:(javascript,c#)