如何从控件验证中仅触发一个实例?

时间:2017-10-09 09:05:00

标签: vb.net controls

我的表单中有5个控件需要验证值是否为空,然后它会显示一个气球工具提示。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    errProvider.Clear()
    Me.ValidateChildren()
End Sub

Private Sub CheckEmptyFields(sender As Object, e As CancelEventArgs) Handles t_customer.Validating, t_judulfile.Validating, t_harga.Validating, cb_bahan.Validating, pgNumRange.Validating
    Dim ctl As Control = CType(sender, Control)
    If ctl.Text = "" Then
        e.Cancel = True
        errProvider.SetIconPadding(ctl, -20)
        errProvider.SetError(ctl, "Please fill the text.")
        showTooltip("Please fill the text.", ToolTipIcon.Warning, "Error", ctl)
    End If
End Sub

但是在我的测试中,代码会在所有空控件中显示工具提示。

The error message says "Please fill the empty field"

我想让工具提示仅指向表单中的第一个或最后一个空控件。

有没有办法只能从所有验证中激活一个实例?

1 个答案:

答案 0 :(得分:1)

以下是我想象的一个例子:

Private controlShowingValidationTip As Control

Private Sub TextBoxes_Validating(sender As Object, e As CancelEventArgs) Handles TextBox3.Validating,
                                                                                 TextBox2.Validating,
                                                                                 TextBox1.Validating
    Dim ctl = DirectCast(sender, Control)

    If ctl.Text = String.Empty Then
        'The control has failed validation.
        e.Cancel = True

        If controlShowingValidationTip Is Nothing OrElse controlShowingValidationTip Is ctl Then
            'Display the validation error tip for this control here.

            controlShowingValidationTip = ctl
        End If
    ElseIf controlShowingValidationTip Is ctl Then
        'This control was showing a validation error tip but has passed validation so clear the tip.

        controlShowingValidationTip = Nothing
    End If
End Sub