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#程序设计有所帮助。