C#中设置textbox限制条件的方法
本文实例讲述了C#中设置textbox限制条件的方法,分享给大家供大家参考。具体实现方法如下:
#region 设置数量等textbox控件样式及限制条件(具体调用的方法就是重写或直接调用ShieldNumberTextBoxOtherKeys函数)
/// <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#程序设计有所帮助。