Home > OS >  Find control by text and assign custom property with Ctype or item is control in dictionary
Find control by text and assign custom property with Ctype or item is control in dictionary

Time:04-13

I have a EmailTextbox like this:

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

I drag it into form and set name is txtEmail. How do i set ValidationError prop in two cases like this:
Case 1:

CType(Me.Controls("txtEmail"), TextBox).ValidationError = 456

Case 2:

Private Items As New Dictionary(Of String, Control) From {
    {"txtEmail", txtEmail}
}
Items("txtEmail").ValidationError = 456

or even shorter:

Me.Controls("txtEmail").ValidationError = 456

Thanks for your answer.

CodePudding user response:

These are some options for achieving what you're looking for.

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
  • Related