C#项目中接触了TextBox只允许输入数字的问题,这倒不难,如下:
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
e.Handled = e.KeyChar < '0' || e.KeyChar > '9'; //允许输入数字
if(e.KeyChar==(char)8) //允许输入回退键
{
e.Handled=false;
}
}
有兴趣的朋友可以看看:
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
string str=this.textBox1.Text;
e.Handled = e.KeyChar < '0' || e.KeyChar > '9'; //允许输入数字
if(e.KeyChar==(char)8) //允许输入回退键
{
e.Handled=false;
}
if(e.KeyChar==(char)46)
{
if(str=="") //第一个不允许输入小数点
{
e.Handled=true;
return;
}
else
{ //小数点不允许出现2次
foreach(char ch in str)
{
if(char.IsPunctuation(ch))
{
e.Handled=true;
return;
}
}
e.Handled=false;
}
}
}
/// <summary>
/// 只能输入数字(含负号小数点)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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;
}
/// <summary>
/// 只能输入正实数
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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;
}
/// <summary>
/// 只能输入整数
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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;
}
/// <summary>
/// 只能输入正整数
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public static void OnlyEnterPlusInt(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 13)
{
e.Handled = true;
}
}