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

TextBox的TextChanged事件设置条件后Button无法重新启用

问题分析与修复

问题根源

你的代码存在两个核心问题导致Button无法重新启用:

  1. 正则表达式语法错误:所有正则中的^[xxx]^写法完全错误,^表示行首,重复使用^会导致正则永远无法匹配任何内容。比如^[A-Za-z]^要求字符串开头是字母后紧跟行首,这不可能实现,导致最后一个启用Button的条件永远不成立。
  2. 代码重复与逻辑不一致:第三个Cost_Txt_TextChanged事件中,检查Item_Txt的正则写成了^[A-Za-z]^,和另外两个事件的^[A-Za-z0-9]^不一致,进一步导致启用条件无法满足。

修复方案

  1. 修正正则表达式,改为匹配整个输入内容的格式:
    • 检查数字输入(Amount_Txt、Cost_Txt):用^\d+$(或^[0-9]+$)确保输入全为数字且非空
    • 检查Item_Txt:用^[A-Za-z0-9]+$确保输入为字母数字组合且非空
  2. 合并重复的事件处理逻辑,减少冗余代码
  3. 调整逻辑判断顺序:先默认禁用Button,只有当所有条件都满足时才启用

修复后的代码

' 合并所有TextBox的TextChanged事件处理
Private Sub ValidateInput(sender As Object, e As EventArgs) Handles Item_Txt.TextChanged, Amount_Txt.TextChanged, Cost_Txt.TextChanged
    ' 先默认禁用Button,满足所有条件后再启用
    Cashout_Btn.Enabled = False

    ' 检查所有输入框是否非空
    If String.IsNullOrEmpty(Item_Txt.Text) OrElse String.IsNullOrEmpty(Amount_Txt.Text) OrElse String.IsNullOrEmpty(Cost_Txt.Text) Then
        Exit Sub
    End If

    ' 检查Amount和Cost是否为纯数字
    Dim isAmountValid As Boolean = System.Text.RegularExpressions.Regex.IsMatch(Amount_Txt.Text, "^\d+$")
    Dim isCostValid As Boolean = System.Text.RegularExpressions.Regex.IsMatch(Cost_Txt.Text, "^\d+$")
    ' 检查Item是否为字母数字组合
    Dim isItemValid As Boolean = System.Text.RegularExpressions.Regex.IsMatch(Item_Txt.Text, "^[A-Za-z0-9]+$")

    ' 所有条件满足时启用Button
    If isAmountValid AndAlso isCostValid AndAlso isItemValid Then
        Cashout_Btn.Enabled = True
    End If
End Sub

额外优化建议

  • 可以使用Integer.TryParse或Decimal.TryParse来检查数字输入,比正则更准确,还能直接获取数值:
    Dim amount As Integer
    Dim isAmountValid As Boolean = Integer.TryParse(Amount_Txt.Text, amount)
    
  • 给TextBox添加输入限制(比如只允许数字输入),减少无效输入的情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.11 22:46:05