public static bool GetNum(string str) //正则表达式判断输入是否为正整数
{
return Regex.IsMatch(str, @"^[1-9]\d*$");
}
private void ui_txt_cyzs_TextChanged(object sender, EventArgs e)//判断输入的是不是正整数
{
if (ui_txt_cyzs.Text == string.Empty)
{
ui_txt_cyzs.Select(ui_txt_cyzs.Text.Length, 0);//选择文本框中的文本范围
}
else if (GetNum(ui_txt_cyzs.Text) == false)
{
ui_txt_cyzs.Text = ui_txt_cyzs.Text.Substring(0, ui_txt_cyzs.Text.Length - 1);
ui_txt_cyzs.Select(ui_txt_cyzs.Text.Length, 0);
}
}
验证输入内容
最新推荐文章于 2024-08-11 17:20:20 发布
该代码片段展示了如何在C#中使用正则表达式判断用户输入的字符串是否为正整数,并进行输入验证。当输入非正整数时,会自动清除尾部非数字字符并高亮显示错误部分。
摘要由CSDN通过智能技术生成