我有一个类似的EmailTextbox:
Imports System.ComponentModel
Public Class EmailTextBox
Inherits TextBox
Private _error As String = ""
Public Sub New()
''
End Sub
Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
Dim brush As New SolidBrush(Me.ForeColor)
e.Graphics.DrawString(Me.Text, Me.Font, brush, 0, 0)
End Sub
Protected Overrides Sub OnValidating(e As CancelEventArgs)
MyBase.OnValidating(e)
Dim isValidEmail As Boolean = ValidatedEmail(Me.Text)
Dim _emailNotValid As String = Global.WindowsApp1.My.Resources.MessageResource.EmailNotValid
Dim _errorBackColor As String = Global.WindowsApp1.My.Resources.MessageResource.ErrorBackColor
e.Cancel = Not isValidEmail Or Me.ValidationError <> ""
'
If Me.ValidationError <> "" Then
_emailNotValid = Me.ValidationError
End If
'
If Not isValidEmail Then
errProvider.SetError(Me, _emailNotValid)
Me.BackColor = ColorTranslator.FromHtml(_errorBackColor)
Else
errProvider.SetError(Me, "")
Me.BackColor = Color.White
End If
End Sub
' custom property for database validation
Public Property ValidationError() As String
Get
Return _error
End Get
Set(ByVal Value As String)
_error = Value
End Set
End Property
End Class
我把它拖到表单中,设置名称为txtEmail。在以下两种情况下,我如何设置ValidationError道具:
情况1:
CType(Me.Controls("txtEmail"), TextBox).ValidationError = 456
案例2:
Private Items As New Dictionary(Of String, Control) From {
{"txtEmail", txtEmail}
}
Items("txtEmail").ValidationError = 456
甚至更短:
Me.Controls("txtEmail").ValidationError = 456
谢谢你的回答。
这些是实现您想要的目标的一些选项。
Private Sub SetValidator()
'if you know that there is only one
Dim myCtrl As EmailTextBox = Me.Controls.OfType(Of EmailTextBox).First
myCtrl.ValidationError = 457
'if you want to find by name
DirectCast(Me.Controls.Find("txtEmail", True)(0), EmailTextBox).ValidationError = 456
End Sub