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#
End RegionDim 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 SubEnd
ClassPublic
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 SubEnd
Class
John WoodPosted May 28, 2009, 9:57 AM
You using the VS2k3 environment? If so, you should be able to implement a KeyPressDown and KeyPressUp. If the KeyPress isnt working usually you can catch the user input on the Down and throw your box and of course Up you would release and resources that you used if they were global from Down.
Also, general rule is dont mess with the form designer file. VS2k3 will just write over what you change.
After looking at your code again...i dont generally follow this format but, this maybe your problem.
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 SubWhy are you encapsulating two similar sections in two different classes? The keyboard event needs to go in the form class and not in an events class....create a code file, not form file, to handle events. When dealing with the visual designer, do not put multiple namespace and classes under a form class. This will cause confusion and will lead to problems of interaction.
I try to keep the form designer namespace/class in its file and if i need to nest namespace/class objects i do them in a codefile seperate from the gui namespace/classes.