博客
关于我
C# 文本框限制大全
阅读量:595 次
发布时间:2019-03-12

本文共 1452 字,大约阅读时间需要 4 分钟。

1.限制输入为数字和字母

在键按事件中,可以通过验证每个按键字符是否为所允许范围内的字母、数字或退格键来实现输入限制。

private void textBox_KeyPress(object sender, KeyPressEventArgs e)  {      if ((e.KeyChar >= 'a' && e.KeyChar <= 'z') || (e.KeyChar >= 'A' && e.KeyChar <= 'Z') || (e.KeyChar >= '0' && e.KeyChar <= '9') || (e.KeyChar == 8))      {          e.Handled = false;      }      else      {          e.Handled = true;      }  }

2.限制输入为数字

为了确保输入仅限于数字字符,可以使用键按事件来执行字符验证。需要注意小数点的处理逻辑,以防止小数点出现在不合适的位置。

private void numberInput_KeyPress(object sender, KeyPressEventArgs e)  {      if ((int)e.KeyChar < 48 || (int)e.KeyChar > 57 || (int)e.KeyChar == 8 || (int)e.KeyChar == 46)      {          e.Handled = true;      }      else      {          // 小数点处理          if ((int)e.KeyChar == 46)          {              if (txtPassWord.Text.Length == 0)                  e.Handled = true;              else              {                  bool b1 = float.TryParse(txtPassWord.Text, out float oldf);                  bool b2 = float.TryParse(txtPassWord.Text + e.KeyChar.ToString(), out float f);                  if (!b2)                  {                      e.Handled = b1 ? true : false;                  }              }          }      }  }

3.限制输入为汉字

在键按事件中,可以使用正则表达式来验证输入是否为汉字字符。

private void txtUserName_KeyPress(object sender, KeyPressEventArgs e)  {      // 验证仅输入汉字      Regex regex = new Regex("[\u4e00-\u9fa5]");      if (!regex.IsMatch(e.KeyChar.ToString()))      {          e.Handled = true;      }  }

转载地址:http://ppkxz.baihongyu.com/

你可能感兴趣的文章
mysql select, from ,join ,on ,where groupby,having ,order by limit的执行顺序和书写顺序
查看>>
MySQL Server 5.5安装记录
查看>>
mysql server has gone away
查看>>
mysql slave 停了_slave 停止。求解决方法
查看>>
MySQL SQL 优化指南:主键、ORDER BY、GROUP BY 和 UPDATE 优化详解
查看>>
MYSQL sql语句针对数据记录时间范围查询的效率对比
查看>>
mysql sum 没返回,如果没有找到任何值,我如何在MySQL中获得SUM函数以返回'0'?
查看>>
mysql Timestamp时间隔了8小时
查看>>
Mysql tinyint(1)与tinyint(4)的区别
查看>>
mysql union orderby 无效
查看>>
mysql v$session_Oracle 进程查看v$session
查看>>
mysql where中如何判断不为空
查看>>
MySQL Workbench 使用手册:从入门到精通
查看>>
mysql workbench6.3.5_MySQL Workbench
查看>>
MySQL Workbench安装教程以及菜单汉化
查看>>
MySQL Xtrabackup 安装、备份、恢复
查看>>
mysql [Err] 1436 - Thread stack overrun: 129464 bytes used of a 286720 byte stack, and 160000 bytes
查看>>
MySQL _ MySQL常用操作
查看>>
MySQL – 导出数据成csv
查看>>
MySQL —— 在CentOS9下安装MySQL
查看>>