我在表单上有20多个文本框,我想知道是否有一种更干净的方法可以用来处理这些控件的验证,而不是使用预期的验证事件处理程序。
我尝试过的是遍历窗体上的所有控件,以检查它们的正确有效值,如果该值无效,则在正确的控件上显示ErrorProvider,从而将20多个事件处理程序缩减为30行代码。此过程位于一个函数中,该函数将返回单击按钮时调用的true或false,如果返回true,则将执行更多逻辑。
我想知道这是否不合适,还是应该坚持验证事件处理程序
最佳答案
当您对所有(或大多数)文本框(如注释中所述)使用相同的验证规则时,可以为这些文本框的Validating
事件分配一个处理程序,并在该处理程序中对其进行验证。例如:
Private Sub TXT_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) _
Handles TextBox1.Validating, TextBox2.Validating, TextBox3.Validating
'Find the validating control
Dim txt As TextBox = DirectCast(sender, TextBox)
'Check validation for that control
If (txt.Text.Length > 10) Then
'Set validation message if the state is invalid
Me.ErrorProvider1.SetError(txt, "Maximum length of text is 10 characters.")
'Say the state is invalid
e.Cancel = True
Else
'Clear probable privious validation error for that textbox
Me.ErrorProvider1.SetError(txt, String.Empty)
End If
End Sub
关于vb.net - 有没有更干净的方法来处理文本框验证事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33844877/