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

C#中TextBox为空时TextChanged事件不执行操作的实现方法

解决TextBox清空时的格式错误问题

问题根源在于当txtQty为空时,int.Parse(txtQty.Text)无法将空字符串转换为整数,从而抛出“Input string was not in a correct format”异常。要实现空文本时不执行任何操作,可以通过以下方式修改代码:

修改后的代码

private void txtQty_TextChanged(object sender, EventArgs e)
{
    // 检测文本是否为空或全空白,满足则直接返回
    if (string.IsNullOrWhiteSpace(txtQty.Text))
        return;

    int cart_qty = 0;
    int inputQty;
    // 安全解析输入的整数,避免非数字文本引发异常
    if (int.TryParse(txtQty.Text, out inputQty))
    {
        if (inputQty + cart_qty > qty)
        {
            MessageBox.Show("无法继续操作,剩余库存数量为 " + qty, "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }
    }
}

关键说明

  • string.IsNullOrWhiteSpace(txtQty.Text):覆盖了文本为空、null或全是空格的情况,只要满足就直接退出方法,不执行后续逻辑。
  • int.TryParse:替代int.Parse,它不会在解析失败时抛出异常,而是返回false,同时兼容非数字输入的场景,让代码更健壮。

内容的提问来源于stack exchange,提问作者John Cloed Guarra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 03:01:00