创建日期:2019-04-24
设置TextBox只能输入整数或数字
/// <summary>
/// 只能输入整数
/// </summary>
private static void tb_KeyPressInt(object sender, KeyPressEventArgs e)
{
//如果输入的不是退格和数字,则屏蔽输入
if (!(e.KeyChar == '\b' || (e.KeyChar >= '0' && e.KeyChar <= '9')))
{
e.Handled = true;
}
}
/// <summary>
/// 只能输入数字
/// </summary>
private static void tb_KeyPressNumber(object sender, KeyPressEventArgs e)
{
//如果输入的不是退格且不能转为小数,则屏蔽输入
if (!(e.KeyChar == '\b' || float.TryParse(((TextBox)sender).Text + e.KeyChar.ToString(), out float f)))
{
e.Handled = true;
}
}
/// <summary>
/// 设置输入框只能输入整数
/// </summary>
public static void SetInputOnlyInt(this TextBox tb)
{
tb.KeyPress += tb_KeyPressInt;
}
/// <summary>
/// 设置输入框只能输入数字
/// </summary>
public static void SetInputOnlyNumber(this TextBox tb)
{
tb.KeyPress += tb_KeyPressNumber;
}
/// <summary>
/// 遍历包含在控件内的控件的集合,设置TextBox的KeyPress事件,只能输入整数
/// </summary>
/// <param name="controls">遍历对象控件</param>
public static void SetTextBoxOnlyInt(this Control ctrl)
{
foreach (Control item in ctrl.Controls)
{
if (item is TextBox)
{
((TextBox)item).KeyPress += tb_KeyPressInt;
}
else
{
SetTextBoxOnlyInt(item);
}
}
}
/// <summary>
/// 遍历包含在控件内的控件的集合,设置TextBox的KeyPress事件,只能输入数字
/// </summary>
/// <param name="controls">遍历对象控件</param>
public static void SetTextBoxOnlyNumber(this Control ctrl)
{
foreach (Control item in ctrl.Controls)
{
if (item is TextBox)
{
((TextBox)item).KeyPress += tb_KeyPressNumber;
}
else
{
SetTextBoxOnlyNumber(item);
}
}
}