简体   繁体   English

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

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

So I know how to do just the textboxes.所以我知道如何只做文本框。 But the validation code will skip within a groupbox, because the control is not within the form.但是验证代码将在组框内跳过,因为控件不在表单内。 I was trying to somehow call the specific groupbox form but I don't know the exact syntax.我试图以某种方式调用特定的 groupbox 表单,但我不知道确切的语法。 Sorry I am new at this, if I don't have enough info please let me know.对不起,我是新手,如果我没有足够的信息,请告诉我。 Also if you have references to control or groupbox commands it would be helpful.此外,如果您有对控制或分组框命令的引用,这将很有帮助。 thanks!谢谢!

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

enter image description here在此处输入图像描述

As per my comments, proper WinForms validation should look like this:根据我的评论,正确的 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

You will now validate all the controls whose Validating event you handle, wherever they are located, and none that you don't.您现在将验证您处理其Validating事件的所有控件,无论它们位于何处,而您不验证任何控件。 If you set CausesValidation to False on all the controls then no validation will occur until you call ValidateChildren .如果在所有控件上将CausesValidation设置为False ,则在调用ValidateChildren之前不会发生验证。 Even if you do want to validate as you go, you should still call ValidateChildren because that will ensure that even those controls that have never received focus will be validated.即使您确实想像 go 一样进行验证,您仍然应该调用ValidateChildren ,因为这将确保即使是那些从未获得焦点的控件也会得到验证。

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

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