简体   繁体   English

Visual Studio:通过TextBox启用/禁用按钮

[英]Visual Studio: Enable/Disable Button Through TextBox

What I am trying to do is when the one of the textboxes is empty the button is disabled, but once the two textboxes are filled-up it will enable the button.. What am I doing wrong? 我想要做的是当其中一个文本框为空时按钮被禁用,但是一旦两个文本框被填满,它将启用按钮..我做错了什么? thank you in advance! 先感谢您!

Public Class ModifiedLoanCalculatorFRM
Private Sub calculateBTN_Click(sender As Object, e As EventArgs) Handles calculateBTN.Click
    If mortgageAmountTBX.Text.Equals("") Or interestRateTBX.Text.Equals("") Then
        calculateBTN.Enabled = False
    Else
        calculateBTN.Enabled = True
    End If

You're putting the code for testing the contents of the text boxes and then setting the enabled state of the button into the button click handler. 您将用于测试文本框内容的代码,然后将按钮的启用状态设置为按钮单击处理程序。 That means that it's only ever going to fire when the button is clicked, and if it ever gets disabled, there's no bringing it back. 这意味着它只会在单击按钮时触发,如果它被禁用,则无法将其恢复。

If your intent is to have the button enable or disable dynamically based on whether or not either of the text boxes is empty, you can move the code from your button click handler into its own subroutine, then make the "Changed" event on both of your text boxes, and your form's load event, call that subroutine: 如果你的意图是根据文本框中的任何一个是否为空来动态启用或禁用按钮,你可以将代码从按钮点击处理程序移动到它自己的子程序中,然后在两个文件框上进行“更改”事件。您的文本框和表单的加载事件,调用该子例程:

Private Sub setButtonState()
    If mortgageAmountTBX.Text.Equals("") Or interestRateTBX.Text.Equals("") Then
        calculateBTN.Enabled = False
    Else
        calculateBTN.Enabled = True
    End If
End Sub

Private Sub interestRateTBX_TextChanged(sender As Object, e As EventArgs) Handles interestRateTBX.TextChanged
    setButtonState()
End Sub

Private Sub mortgageAmountTBX_TextChanged(sender As Object, e As EventArgs) Handles mortgageAmountTBX.TextChanged
    setButtonState()
End Sub

Private Sub ModifiedLoanCalculatorFRM_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    setButtonState()
End Sub

You can use: 您可以使用:

Private Sub TextBoxes_TextChanged(sender As Object, e As EventArgs) _
    Handles TextBox1.TextChanged, TextBox2.TextChanged, MyBase.Load
    Button1.Enabled = Not (String.IsNullOrEmpty(TextBox1.Text) OrElse
                           String.IsNullOrEmpty(TextBox2.Text))
End Sub

Notes about above code: 关于上述代码的说明:

  • Use a single event handler for multiple controls 对多个控件使用单个事件处理程序
  • Use String.IsNullOrEmpty to check if the text is empty 使用String.IsNullOrEmpty检查文本是否为空
  • Use OrElse instead of Or 使用OrElse而不是Or
  • Set Enabled property with a single expression. 使用单个表达式设置Enabled属性。

创建一个计时器,并在表单运行时启动它,将此代码放在计时器刻度上

If INSERTTEXTBOXNAMEHERE.text = "" Then INSERTBUTTONNAMEHERE.enabled = false Else INSERTBUTTONNAMERHERE.enabled = True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM