如何使用控件验证组框中的文本框



所以我知道如何做只是文本框。但是验证代码将在组框中跳过,因为控件不在表单中。我试图以某种方式调用特定的组框形式,但我不知道确切的语法。对不起,我是新来的,如果我没有足够的信息,请让我知道。此外,如果您有控制或组框命令的引用,这将是有帮助的。谢谢!

For Each cntrl As Control In Controls
If TypeOf cntrl Is TextBox Then
cntrl.BackColor = Color.White
If cntrl.Text = String.Empty Then
cntrl.BackColor = Color.Yellow
cntrl.Focus()
Return False
End If
For Each cntrl As GroupBox In Controls
If TypeOf cntrl Is TextBox Then
cntrl.BackColor = Color.White
If cntrl.Text = String.Empty Then
cntrl.BackColor = Color.Yellow
cntrl.Focus()
Return False
End If

输入图片描述

根据我的评论,正确的WinForms验证应该是这样的:

Private Sub TextBoxes_Validating(sender As Object, e As CancelEventArgs) Handles TextBox3.Validating,
           TextBox2.Validating,
           TextBox1.Validating
Dim tb = DirectCast(sender, TextBox)
If tb.TextLength = 0 Then
tb.BackColor = Color.Yellow
e.Cancel = True
Else
tb.BackColor = SystemColors.Window
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If ValidateChildren() Then
'All controls contain valid data so go ahead and use it.
End If
End Sub

您现在将验证您处理其Validating事件的所有控件,无论它们位于何处,以及您不处理的控件。如果在所有控件上设置CausesValidationFalse,则在调用ValidateChildren之前不会发生验证。即使你确实想要验证,你仍然应该调用ValidateChildren,因为这将确保即使那些从未收到焦点的控件也将被验证。

相关内容

最新更新