C#中设置textbox限制条件的方法
本文实例讲述了C#中设置textbox限制条件的方法,分享给大家供大家参考。具体实现方法如下:
/// <summary>
/// 屏蔽数字textbox的其他字符串
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public virtual void tBoxNumbers_KeyDown(object sender, KeyEventArgs e)
{
e.SuppressKeyPress = true;
switch (e.KeyCode)
{
case Keys.D0:
case Keys.D1:
case Keys.D2:
case Keys.D3:
case Keys.D4:
case Keys.D5:
case Keys.D6:
case Keys.D7:
case Keys.D8:
case Keys.D9:
case Keys.NumPad0:
case Keys.NumPad1:
case Keys.NumPad2:
case Keys.NumPad3:
case Keys.NumPad4:
case Keys.NumPad5:
case Keys.NumPad6:
case Keys.NumPad7:
case Keys.NumPad8:
case Keys.NumPad9:
case Keys.Back:
case Keys.OemPeriod:
case Keys.Delete:
case Keys.Decimal:
e.SuppressKeyPress = false;
break;
default:
break;
}
}
public virtual void tBoxNumbers_KeyPress(object sender, KeyPressEventArgs e)
{
TextBox tBox = sender as TextBox;
char c = e.KeyChar;
if (c.ToString().Equals("."))
{
if (tBox.Text.Length <= 0)
e.Handled = true; //小数点不能在第一位
else
{
float f;
float oldf;
bool b1 = false, b2 = false;
b1 = float.TryParse(tBox.Text, out oldf);
b2 = float.TryParse(tBox.Text + e.KeyChar.ToString(), out f);
if (b2 == false)
{
if (b1 == true)
e.Handled = true;
else
e.Handled = false;
}
}
}
}
/// <summary>
/// 屏蔽数字textbox的其他字符串
/// </summary>
/// <param name="tbox">要屏蔽的textbox</param>
public virtual void ShieldNumberTextBoxOtherKeys(TextBox tbox)
{
tbox.ImeMode = ImeMode.Disable;
tbox.KeyDown += tBoxNumbers_KeyDown;
tbox.KeyPress += tBoxNumbers_KeyPress;
}
#endregion
希望本文所述对大家的C#程序设计有所帮助。
上一篇:C#实现的SN快速输入工具实例
栏 目:.NET代码
下一篇:C#实现输入法功能详解
本文标题:C#中设置textbox限制条件的方法
本文地址:http://www.codeinn.net/misctech/21112.html