TextBoxes和启用按钮

时间:2014-07-26 10:42:53

标签: vb.net

我正在创建一个程序,其中有三个文本框和一个计算按钮,如果所有三个文本框中都有值,我只希望启用计算按钮。这是我目前使用的代码,但即使所有三个文本框都为空,按钮也会保持启用状态

 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    FirstNumber = CInt(TextBox1.Text)
    SecondNumber = CInt(TextBox2.Text)
    ThirdNumber = CInt(TextBox3.Text)
    Result = (SecondNumber - FirstNumber) / ThirdNumber
    Label5.Text = Result
    If TextBox1.Text = "" And TextBox2.Text = "" And TextBox3.Text = "" Then
        Button1.Enabled = False
    End If

如何解决问题?

3 个答案:

答案 0 :(得分:1)

所有3个文本框只有一个事件处理程序 在事件代码中,检查文本框的值并设置布尔值以启用或不启用按钮

Private Sub textBoxes_Validating(ByVal sender As Object, _
               ByVal e As System.ComponentModel.CancelEventArgs) _
               Handles textBox1.Validating, textBox2.Validating, textBox3.Validating

  Dim areValid As Boolean = True
  Dim intValue As Integer

  if Not Int32.TryParse(textBox1.Text, intValue) Then
      areValid = false
  else if Not Int32.TryParse(textBox2.Text, intValue) Then
      areValid = false
  else if Not Int32.TryParse(textBox3.Text, intValue) Then
      areValid = false
  End If
  Button1.Enable = areValid
  ' You could force the focus to remain on the invalid textbox enabling this line
  ' e.Cancel = True
End Sub 

答案 1 :(得分:0)

您必须为每个文本框的text_changed事件编写代码。当输入文本时,该按钮不知道文本框中发生了什么......

连接text_changed事件,你必须评估来自所有三个文本框的所有3个文本框'文字改变了事件。相应地禁用您的按钮。

答案 2 :(得分:0)

将所有3个文本框的TextChange事件放在TextBox1_TextChanged上 它将检查它是否只包含数字。“如果不在其他地方再次禁用按钮”
当然,按钮需要在开始时禁用。

而且我也不知道你是否想拥有像1.2这样的数字然后在下面的代码中使用Double“”

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged, TextBox3.TextChanged, TextBox2.TextChanged
    If IsNumeric(TextBox1.Text) = True And IsNumeric(TextBox2.Text) = True And IsNumeric(TextBox3.Text) = True Then
        Button1.Enabled = True
    Else
        Button1.Enabled = False
    End If
End Sub

Dim FirstNumber As Double
Dim SecondNumber As Double
Dim ThirdNumber As Double
Dim Result As Double

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    FirstNumber = CDbl(TextBox1.Text)
    SecondNumber = CDbl(TextBox2.Text)
    ThirdNumber = CDbl(TextBox3.Text)
    Result = (SecondNumber - FirstNumber) / ThirdNumber
    Label5.Text = Result
End Sub
相关问题