1
Reply

Using Events in VB.net 2003

Mark

Mark

May 27 2009 3:19 PM
3.5k

Please help! I'm new to vb.net and I am having trouble understanding events or at least getting them to work. I am using a self guided book and they ask you to raise an event to display and messagebox if the user types an 'x' into a text box. I was able to get this to work using keypress without raising an event.  When i try to use an event I get error that 'Handles clause requires a WithEvents variable .  As I see it TextBox2 is declared "WithEvents"  The error is displayed for the TextBox2 portion of the following code which I coded in red below 'TextBox2.KeyPress'

 

Thanks

Public WithEvents TextBox2 As System.Windows.Forms.TextBox

<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

Me.TextBox2 = New System.Windows.Forms.TextBox

Me.SuspendLayout()

'

'TextBox2

'

Me.TextBox2.Location = New System.Drawing.Point(88, 72)

Me.TextBox2.Name = "TextBox2"

Me.TextBox2.Size = New System.Drawing.Size(192, 20)

Me.TextBox2.TabIndex = 0

Me.TextBox2.Text = ""

'

'Form1

'

Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)

Me.ClientSize = New System.Drawing.Size(464, 318)

Me.Controls.Add(Me.TextBox2)

Me.Name = "Form1"

Me.Text = "Form1"

Me.ResumeLayout(False)

End Sub

#End Region

 

Dim WithEvents Xchecker As New newEvent

 

 

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

End Sub

Private Sub Xchecker_Xwarning(ByVal Text As String) Handles Xchecker.Xwarning

MessageBox.Show(Text)

End Sub

End Class

Public Class newEvent

Public Event Xwarning(ByVal Text As String)

Public Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress

If e.KeyChar = "x" Then

RaiseEvent Xwarning("Warning - you pressed the x key")

End If

End Sub

End Class


Answers (1)