C#中设置textbox限制条件的方法

时间:2021-05-20

本文实例讲述了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#程序设计有所帮助。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章