You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用char.IsDigit禁止文本框输入0?现有代码无法实现需求

解决方案

你只需要修改判断条件,把数字中的'0'排除即可,修改后的代码如下:

private void TxtNumber4_KeyPress(object sender, KeyPressEventArgs e)
{
    // 允许非0的数字,或者控制键(比如退格)
    if ((char.IsDigit(e.KeyChar) && e.KeyChar != '0') || char.IsControl(e.KeyChar))
    {
        errorProvider1.SetError(LblNum2, "");
        LblNum2.Text = "";
    }
    else
    {
        e.Handled = true;
        errorProvider1.SetError(LblNum2, "仅允许输入非0的数字!");
        LblNum2.Text = "仅允许输入非0的数字!";
    }
}

关键修改说明:

  • 将原条件里的char.IsDigit(e.KeyChar)替换为char.IsDigit(e.KeyChar) && e.KeyChar != '0',直接排除输入'0'的情况
  • 移除了多余的(int)e.KeyChar == 0判断,因为char.IsControl已经涵盖了退格、删除等各类控制按键
  • 更新错误提示文本,让用户明确知道仅能输入非0数字

内容的提问来源于stack exchange,提问作者MPC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 14:05:22