VB.NET: WithEvents not Working

Posted by Hei on Stack Overflow See other posts from Stack Overflow or by Hei
Published on 2010-04-21T23:56:17Z Indexed on 2010/04/22 0:03 UTC
Read the original article Hit count: 151

Filed under:

Hello All, I have the following classes:

Public Class Email

    Private Shared ReadOnly EMAIL_REGEX = "\b[a-zA-Z]+[a-zA-Z0-9._+-]+@" + _
                                      "[a-zA-Z0-9.-]+\.[a-zA-Z]{2,3}\b"
    Private _email As String

    Public Event emailCreated()

    ' Declare empty constructor private so the only way to create an object
    ' is using new (email)
    Private Sub New()

    End Sub

    Sub New(ByVal email As String)
        If Regex.IsMatch(email, EMAIL_REGEX) Then
            _email = email
            RaiseEvent emailCreated()
        Else
            Throw New Exception("Email Not Valid")
        End If
    End Sub

    ReadOnly Property Email() As String
        Get
            Return _email
        End Get
    End Property

End Class

And

Public Class EmailForm

    WithEvents myEmail As Email

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Try
            myEmail = New Email(TextBox1.Text)
        Catch ex As Exception
            MessageBox.Show("Exception: " & ex.Message)
        End Try
    End Sub

    Public Sub emailCreated() Handles myEmail.emailCreated
        MessageBox.Show("New Email Created")
    End Sub

End Class

If a create a wrong email lets say "email" the exception is correctly cached and a message is showed however is i input a valid email the event is not raised, the object is being created but no message is shown and no error or exception is thrown i suspect it has something to do with using "myemail = new Email(email)" but i have seen examples of using new with withevents with no problem. I would apreciate any input about this problem

thank you

© Stack Overflow or respective owner

Related posts about vb.net