How to get event name in vb.net? - vb.net

Here there are two handlers in a particular procedure then how to get which event handler has performed.
for example
Private Sub TextBox1_Events(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged, TextBox1.GotFocus
End Sub
how to get which event has occured.

It is possible using the StackTrace (could be a better way I'm not sure...). Try the following code.
Private Sub TextBox1_Events(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged, TextBox1.GotFocus
Dim s As New StackTrace(True)
For Each f As StackFrame In s.GetFrames
Debug.WriteLine(f.GetMethod.Name)
Next
End Sub
When the text box gets focus the following is written:
TextBox1_Events
OnGotFocus
OnGotFocus
WmSetFocus
Ect…….
Where as when it’s a text changed event
TextBox1_Events
OnTextChanged
OnTextChanged
Ect….
I’m sure you could write something using this to do what you need. But i fully agree with the other guys separate handlers is better.

In this case, you cannot.
If the events were bound to two separate controls, you could check the sender property for the type
If the e argument for the event had some type other than EventArgs (some events use a different arguments type), or the control passed some type derived from EventArgs, then you might be able to check properties on that variable
There aren't any other tricks you could use because events don't provide any sort of data to the handler specifying which event occurred.
With these two events, they're both going to be sent from the same text box, so the first option is out. Also, with both events, they send just an instance of the EventArgs class (not a derived class), so that option is out.
Ultimately, you're going to have to have multiple event handlers to solve this specific problem.

It's not possible. If you're in a situation where you need to know which event occurred, you will always be better off using two separate handlers.

Since you are dealing with 2 events (similar in signature) emitted by the same control the easiest/cleanest way of solving this would be 2 separate event handlers (as suggested by Merlyn Morgan-Graham):
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
'the TextChanged specific code would go here
HandletTextBox1EventInternal(sender, e)
End Sub
Private Sub TextBox1_GotFocus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.GotFocus
'the GotFocus specific code would go here
HandletTextBox1EventInternal(sender, e)
End Sub
Private Sub HandleTextBox1EventInternal(ByVal sender As System.Object, ByVal e As System.EventArgs)
'code common to GotFocus and TextChanged handlers
End sub

Related

System.InvalidCastException was unhandled Error

I have received the error as stated in my title and being a new user to vb.net trying to make sense of it. I would be grateful if someone could explain the correct way to troubleshoot this error as I am not experienced enough to know where to start with this type of error.
If it helps, this is what I am trying to do. I have a contextmenu in a listbox that when I right click on an entry, displays the value of the member in that cell. The messagebox appears with the correct value, but when I click to close the box, this error appears. Many thanks
Unable to cast object of type 'System.EventArgs' to type 'System.Windows.Forms.ToolStripItemClickedEventArgs'.
This is the code I think I should show.
Private Sub HideToolStripMenuItem_Click(ByVal sender As Object, ByVal e As ToolStripItemClickedEventArgs) Handles pnlContextMenuStrip1.ItemClicked, HideToolStripMenuItem.Click
'Get the text of the item that was clicked on.
Try
MessageBox.Show(txtCustomerActive.Text)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub ContextMenuStrip1_Opening_1(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles pnlContextMenuStrip1.Opening
End Sub
UPDATE: I enabled Stirct On in my project and after making some minor changes to the code I am left with this which I think refers to the error.
Error 1 Method 'Private Sub HideToolStripMenuItem_Click(sender As Object, e As System.Windows.Forms.ToolStripItemClickedEventArgs)' cannot handle event 'Public Event Click(sender As Object, e As System.EventArgs)' because they do not have a compatible signature. C:\Users\domain\Documents\Visual Studio 2010\Projects\Login\btLogin\vb\Form2.vb 153 175 Login
The ToolStripItem.Click-event has this parameters:
(object sender, EventArgs e)
ToolStripItemClickedEventArgs inherits from System.EventArgs, so it's implicitely of type EventArgs. A child has all abilities of it's parent but not vice-versa.
I assume you simply have to change that signature to:
Private Sub HideToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles pnlContextMenuStrip1.ItemClicked, HideToolStripMenuItem.Click
So just change ToolStripItemClickedEventArgs to EventArgs.

Creating a way to handle textbox validation

I have a time entry form that contains a tabcontrol with tab pages for each day of the week. Within this control is a table layout panel that is holding together various textboxes/labels. For each day of the week, the inputs are named in a similar fashion:
txtMonWorkHours
txtMonPTOHours
txtMonOTHours
txtTuesWorkHours
txtTuesPTOHours
txtTuesOTHours
...
I am using ADO.net to load/save all these values from a database into their respective textboxes.
What I am now trying to do now is provide a method to validate entry (which I have now finished on an individual event basis such as:
Private Sub txtMonIn_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtMonIn.Leave
ValidateTimeEntered(txtMonIn)
End Sub
and
Private Sub txtMonIn_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtMonIn.TextChanged
TransitionTextPreValidate(txtMonIn)
End Sub
My question is: Is there a way to add the method I have created to all the textboxes I need without having to assign each method to each textbox event individually?
Your events have the ability to handle multiple controls, that is why the "sender" object is passed, so you know who is calling the event. Try this, notice the end of the sub's declaration:
Private Sub txtWeekdayIn_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtMonIn.Leave, txtTueIn.Leave, txtWedIn.Leave
ValidateTimeEntered(sender)
End Sub

Running event x from event y

(Newbie VB.NET question)
Here's the specific code behind my simple winforms that I don't fully understand:
Private Sub okButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles okButton.Click
'do something
End Sub
Private Sub MainForm_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Enter
okButton_Click(Me, e) '<=== argumanets must be wrong
End Sub
What I'm trying to achieve:
If the user hits Enter when they have the winforms active then I'd like the Click event handler of the okButton to fire.
Obviously from the above my understanding of the arguments I need to supply to the event called okButton_Click is lacking; what are the correct arguments and why?
I think you might use the AcceptButton property of the form. Just set it to the desired button and it should do the trick.
Note that there is also a CancelButton property.
Answering your event-question:
The sender argument marks the sender of the event. Mostly, this is the Me instance of the class. In my opinion, Me seems to be absolutely correct.
The e argument contains the EventArgs of the specific event. If you're not using this argument in your function body, the content of this variable doesn't matter. You could use Nothing or just route the EventArgs (that's what you've done).
Refering to your comment:
EventArgs is a base class for event-specific data. For example, if you're subscribing to a mouse event, ewill be a MouseEventArgs. The MouseEventArg class offers you the mouse buttons that have been pressed and the coordinates of the pointer when the event was fired.
In your case, the events only have EventArgs which provide only basic information about the event. There does not seem to be special information about it.
Note: If you want to combine multiple events into one callback, you can make e of type EventArgs because every e should inherit from EventArgs following the Microsoft guidelines. Therefore, you can combine a Button-Click with a Mouse-Move into one callback because the signature of the delegates match.
A nicer way than just passing Nothing to the target Sub, is to combine two callbacks into one. You can do this in VB.NET using multiple Handles like this:
Private Sub SomeSub(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles okButton.Click, MyBase.Enter
'this is getting called on a okButton.Click and MyBase.Enter
End Sub
(Scroll to the right to see the Handles)
Note that you don't need a second Sub which calls the first one. Everything is in one Sub.
Try this instead:
Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, keyData As System.Windows.Forms.Keys) As Boolean
If (keyData And Keys.KeyCode) = Keys.Enter Then
okButton.PerformClick()
Return True
End If
Return MyBase.ProcessCmdKey(msg, keyData)
End Function
You might need to exclude some controls in the check if you want to use enter key with other controls, ie:
If (keyData And Keys.KeyCode) = Keys.Enter AndAlso Not Textbox1.Focused Then

Event Handles Button.Click

Hello here is what i want to do:
Private Sub UpdateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UpdateButton.Click
MyUpdate.CheckUpdate("version.txt")
If MyUpdate.CurrentVersion < MyUpdate.UpdateVersion Then
'IF USER PRESS THE BUTTON TO RAISE EVENT ONE MORE TIME
Else
'DO NOTHING
End If
End Sub
I don't know how to raise an event within an event. Thank you!
Intuitively enough, you use the RaiseEvent keyword.
More explanation about raising and consuming events in VB.NET can be found here on MSDN.
But in this case it's probably better to refactor your code and extract the logic out of event handler method into another function.

Textbox click event in vb.net

I am trying to write an onclick event for textbox but VB.net does not seem to support textbox1.click()
I want to open a new form every time someone clicks on the textbox.
Opening a new form is no problem, but I cant detect the click.
Is there any event for textbox that detects click event?
I saw something like TextboxBase that has Click but I am able to use it well.
please help!
This is how my class looks :
Partial Public Class TextBoxClick
Inherits System.Web.UI.Page
End Class
It has some basic load and init events.
I am trying to write a Sub like this :
Private Sub incident_clicked(ByVal sender As Object, ByVal e As System.EventArgs) Handles Incident.OnClick
Incident.Click does not work either.
I am guessing I need to import some class to access the Click event but I am not sure which.
Thanks is advance
TextBox has a Click event, using it is no problem. Your Handles clause however uses OnClick, that's not a valid event name. Do make sure this Sub is inside a Form class and not a module.
Public Class Form1
Private Sub TextBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.Click
MessageBox.Show("Click!")
End Sub
End Class
You could use onFocus event :)
According to MSDN, your code should work as follows:
Private Sub TextBox1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles TextBox1.Click
' Code to handle the event here
End Sub
However, you could also try the MouseUp event:
Private Sub textbox1_MouseUp(sender As Object, _
e As System.Windows.Forms.MouseEventArgs) _
Handles textbox1.MouseUp
' Code to handle the event here
End Sub
' Will fire if textbox gets focused
Private Sub incident_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles incident.GotFocus
Debug.Print("inciden got focus")
End Sub
' Will fire if textbox gets mouse clicked
Private Sub incident_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles incident.MouseClick
Debug.Print("inciden got clicked")
End Sub
For anyone who is having trouble with this, I fixed it by switching to an asp control. My button now looks like this:
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
Not sure why, but I now have a working click event.
For me the Textbox_ click event is triggered only when I type a character in that box.
The textbox click event is triggered only when you type a character in that textbox.
That is disgusting. You may want to try mouse-enter mouse-leave events they are more reliable. Babu V Bassa.