繁体   English   中英

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

[英]How do I validate text boxes with in a a group box using control

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

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事件的所有控件,无论它们位于何处,而您不验证任何控件。 如果在所有控件上将CausesValidation设置为False ,则在调用ValidateChildren之前不会发生验证。 即使您确实想像 go 一样进行验证,您仍然应该调用ValidateChildren ,因为这将确保即使是那些从未获得焦点的控件也会得到验证。

暂无
暂无

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

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