我有9个文本框,名为Textbox1
,一直到Textbox9
。我还有一个名为Letter
的按钮,它从数组中选择一个随机字母。我有另一个名为Start
的按钮。按下此按钮会显示一个从30秒倒计时到零的计时器。我希望只有当所有9个文本框中都包含文本时才会发生此按钮。我尝试了以下但它似乎不起作用:
答案 0 :(得分:1)
将if语句中的所有“和”更改为“或”
Private Sub BtnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStart.Click
If TxtBox1.Text = "" Or TxtBox2.Text = "" Or TxtBox3.Text = "" Or
TxtBox4.Text = "" Or TxtBox5.Text = "" Or TxtBox6.Text = "" Or
TxtBox7.Text = "" Or TxtBox8.Text = "" Or TxtBox9.Text = "" Then
TmrGame.Enabled = False
MessageBox.Show("There Must Be A Total Of Nine Letters To Start The Game", "Not Enough Letters")
Else
TmrGame.Enabled = True
End If
End Sub
通过使用And,您检查所有文本框必须为空,然后您将设置timer.Enabled为false。使用Or,您说如果任何文本框为空,您将设置timer.Enabled为false。
答案 1 :(得分:1)
Shar1er80的回答是正确的。另一种方法是在任何文本框的文本发生更改后启用或禁用该按钮。您可以使用事件处理程序轻松完成此操作:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim Boxes As TextBox() = {TextBox1, TextBox2, TextBox3, TextBox4, TextBox5, TextBox6, TextBox7, TextBox8, TextBox9}
For Each b In Boxes
AddHandler b.TextChanged, Sub(s, ee)
btnStart.Enabled = Not Boxes.Any(Function(box) box.Text = "")
'The same, not using a negation would be:
'btnStart.Enabled = Boxes.All(Function(box) box.Text <> "")
End Sub
Next
End Sub
首先,我创建一个包含所有文本框的数组。它们就像其他任何东西一样。然后我使用AddHandler
关键字将每个框的TextChanged
事件连接到子。
在Sub中,我使用LINQ检查是否有任何文本框为空,如果是,则禁用该按钮(这类似于检查or
连接的If语句中的每个框。)
答案 2 :(得分:0)
尝试这样的事情:
Option Strict On
Option Explicit On
Option Infer Off
Public Class Form1
Private Sub BtnStart_Click(sender As Object, e As EventArgs) Handles BtnStart.Click
Dim execute As Boolean = True
For i As Integer = 1 To 9
If DirectCast(Me.Controls("TextBox" & i.ToString), TextBox).Text = "" Then execute = False
Next
If execute Then
'Your code to execute here
Else
MessageBox.Show("Please provide input in all fields.", "Incomplete Submission", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
End Sub
End Class