e.target in VB.net - vb.net

When using flash, I was able to get to the focus of an event by accessing the event's "target" attribute.
so if I remember, it was something similar to.
button1.addEventListener(mouse_click, doSomething);
doSomething(e: Event){
e.target.size = 50000;
}
And I'm looking for the equivalent in VB.
If you can give me it's common name across all languages, I'd be doubly grateful. I don't quite know what to search for aside from "event.target VB.net equivalent, and that's not returning anything.
Thanks in advance.
edit: for those new to flash. By focus, I mean the physical object that was clicked on. So the example given would be accessing the clicked button's size.

In VB you can wire up event handlers declaratively using the WithEvents keyword or imperatively using AddHandler.
Private WithEvents myButton
' OR
Public Sub New
Dim newButton = New Button()
AddHandler newButton.Click, AddressOf MyClickHandler
End New
'To consume it you declare a method as follows:
' The Handles clause is used when declaring WithEvents
Private Sub MyClickHandler(sender As Object, e As EventArgs) Handles myButton.Click
' The sender has a handle on the object that raised the event (aka the button)
Dim btn = DirectCast(sender, Button)
btn.Size = New Size(500, 500)
End Sub

Got it!
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclick.aspx#Y0
Sub GreetingBtn_Click(ByVal sender As Object, ByVal e As EventArgs)
'When the button is clicked,
'change the button text, and disable it.
Dim clickedButton As Button = sender
clickedButton.Text = "...button clicked..."
clickedButton.Enabled = False
End Sub
The first parameter (sender by default) references the focused object. You can access it as you would any other normal variable, but it's information won't appear in the auto complete list unless you set it "As" that specific data type.
So I ended up with this
Private Sub nw_btn_Click(ByVal sender As System.Windows.Forms.Button, ByVal e AsSystem.EventArgs) Handles nw_btn.Click
sender.Hide()
End Sub

Related

How can I find the sender of ContextMenuStrip?

Situation:
I have a context menu in a VB.NET form with fires an event handler on ItemClicked. The auto-generated subroutine receives sender and e as parameters. As I don't reinvent the wheel multiple times, I linked this context menu to three text boxes. Let's name them Textbox1, Textbox2 and Textbox3.
Problem: How can I figure out in which textbox the menu was opened?
Okay, what did I already try?
sender contains the menu itself,
e.ClickedItem just returns the single menu item that was selected.
sender.Parent is always nothing
sender.OwnerItem is also always Nothing`
Me.Textbox1.Focused is always False, even if its the "parent" control of the menu.
Okay, I found a solution that works fine, and here's the code for all VB.NET coders that have the same problem.
The context menu is linked in TextBox1, so we need to add another event handler that saves the sending control into the menu:
Private Sub TextBox1_MouseUp(sender As Windows.Forms.Control, e As System.Windows.Forms.MouseEventArgs) Handles TextBox1.MouseUp
If e.Button = Windows.Forms.MouseButtons.Right Then
ContextMenu.Tag = sender
End If
End Sub
And this is the code of the event handler when clicking a menu item:
Private Sub ContextMenu_ItemClicked(sender As System.Object, e As System.Windows.Forms.ToolStripItemClickedEventArgs) Handles ContextMenu.ItemClicked
ContextMenu.Close()
If ContextMenu.Tag Is Nothing Then
Debug.Print("debug info: forgot to set sender? well ... KABOOM!")
Exit Sub
End If
Dim oParent As Windows.Forms.Control
Try
oParent = ContextMenu.Tag
Catch ex As Exception
Debug.Print("debug info: tag contains data other than sender control. well ... KABOOM!")
Exit Sub
End Try
' Do fancy stuff here.
' Release sender
ContextMenu.Tag = Nothing
End Sub
The ContextMenuStrip has a SourceControl property which contains a reference to the control which opened the menu. The event fires from one of the ToolStripMenuItems in the ContextMenuStrip, so you have to get the "parent" first:
' cast sender to menuitem
Dim mi = CType(sender, ToolStripMenuItem)
' cast mi.Owner to CMS
Dim cms = CType(mi.Owner, ContextMenuStrip)
' the control which opened the menu:
Console.WriteLine(cms.SourceControl.Name)
Under certain conditions the SourceControl can get lost but you can track it yourself with a variable and the parent ContextMenuStrip Opening event:
' tracking var:
Private MenuSourceControl As Control
Private Sub cms_Opening(sender As Object, e As CancelEventArgs) Handles cms.Opening
' set reference in case/before it is lost
MenuSourceControl = CType(sender, ContextMenuStrip).SourceControl
End Sub
Private Sub CutToolStripMenuItem_Click(sender...
If MenuSourceControl IsNot Nothing Then
' do your stuff
' optionally clear the tracking var
MenuSourceControl = Nothing
End If
End Sub
It should be also easier to get the SourceControl when dealing with sub items
You can also capture the related control in the MouseDown event of the related Control in cases where the same menu is used with different controls:
Private Sub lv2_MouseDown(sender As Object,
e As MouseEventArgs) Handles lv2.MouseDown,
myLV.MouseDown, lv1.MouseDown ...
If e.Button = Windows.Forms.MouseButtons.Right Then
MenuSourceControl = DirectCast(sender, Control)
End If
End Sub

SelectionChanged Event For Regular TextBox?

I've been doing some research and I can't seem to find any type of event for SelectionChanged for a regular textbox. Can anyone please help me with this. I do not want to use a RichTextBox. Thanks
Please refer to the link below:
TextBox.SelectionChanged Event - MSDN
Occurs when the text selection has changed.
'Declaration
Public Event SelectionChanged As RoutedEventHandler
By listening to the MouseUp event of the TextBox, you can roughly get a similar behavior :
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddHandler TextBox1.MouseUp, AddressOf TextBox1_OnMouseUp
End Sub
Private Sub TextBox1_OnMouseUp(ByVal sender As Object, ByVal e As MouseEventArgs)
Dim textBox As TextBox = DirectCast(sender, TextBox)
Dim selectedText As String = textBox.SelectedText
Console.WriteLine(selectedText)
End Sub
End Class
Result:
Edit:
Additionally, to properly react during double-clicks, you can encompass your code with the following safe-guard, it will ensure to not output false positives during the first click.
Dim isNullOrEmpty As Boolean = String.IsNullOrEmpty(selectedText)
If Not isNullOrEmpty Then
Console.WriteLine(selectedText) // your code
End If

Handle an event of a control defined on another form

I have a form declared as s property WithEvents. If I add Handles formServers.FormClosing to a Sub declaration it works fine, but when I want to handle an event of a control within formServers I get the following error -
'Handles' in classes must specify a 'WithEvents' variable.
How do I correctly set this up? Thanks.
Private WithEvents formServers As New formServers
Private Sub txtServers_Closing(ByVal Sender As Object,
ByVal e As EventArgs) Handles formServers.txtServers.LostFocus
Me.SetServers()
If Me.ServersError Then
Dim Ex As New Exception("Error validating Servers.")
Dim ErrorForm = New formError(Ex, 101)
End If
End Sub
The error message is fairly misleading. The Handles keyword has several restrictions, it cannot work across different classes, it needs an object reference. You must use the more universal AddHandler keyword instead.
There are some additional problems in your scenario. Never use the LostFocus event, use Leave instead. And it is very important that you subscribe the event for the specific instance of the form, using As New gets you into trouble when you display the form multiple times, an ObjectDisposedException will be the outcome. Correct code looks like this:
Private formInstance As FormServers
Private Sub DisplayFormServer()
formInstance = new FormServers
AddHandler formInstance.txtServers.Leave, AddressOf txtServers_Closing
AddHandler formInstance.FormClosed, _
Sub()
formInstance = Nothing
End Sub
formInstance.Show()
End Sub
A much more elegant approach is to expose the event explicitly in your FormServers class. Make that look like this:
Public Class FormServers
Public Event ServersLeave As EventHandler
Private Sub txtServers_Leave(sender As Object, e As EventArgs) Handles txtServers.Leave
RaiseEvent ServersLeave(Me, EventArgs.Empty)
End Sub
End Class
The problem is that you do are not specifying WithEvents on the TextBox. Rather, you are specifying WithEvents on the Form. You can only use Handles on variables which you have declared directly with the WithEvents keyword. With the WithEvents being on the form, you will only be able to use Handles to handle events that are raised directly by the form itself. You will not be able to do so for events raised by any of its controls.
You can fix this in one of two ways. Either you can use AddHandler to register your event handler (rather than using the Handles keyword), or you can create a TextBox variable WithEvents and then set it to the appropriate TextBox object on the form, like this.
Private formInstance As New FormServers
Private WithEvents txtServers As TextBox
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
txtServers = formServers.txtServers
End Sub
Private Sub txtServers_LostFocus(Sender As Object, e As EventArgs) Handles txtServers.LostFocus
' ...
End Sub
The advantage of the latter approach, besides the more consistent, and possibly more elegant syntax, is that you don't have to remember to call RemoveHandler.

VB.NET MDI Child set other child property

I hope you can help my trouble.
I have 1 form as parent MDI (frmParent.vb) and have 2 child form (frmChild01.vb & frmChild02.vb).
the code for parent form as per below.
Private Sub OpenChild01ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenChild01ToolStripMenuItem.Click
Dim child01 As frmChild01
child01 = New frmChild01()
child01.MdiParent = Me
child01.Show()
End Sub
Private Sub OpenChild02ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenChild02ToolStripMenuItem.Click
Dim child02 As frmChild02
child02 = New frmChild02()
child02.MdiParent = Me
child02.Show()
End Sub
frmChild01 have button1
frmChild02 have label1
My problem is how can I set label1.text when user click button1
Thanks in advance...
There are a lot of creative ways you can do this; but ultimately you need to provide a communication channel between Child1 and Child2.
The most direct way would be to Pass a Reference of frmChild02 to frmChild01. You'd need label1 to be public so that frmChidl02 can access it (or you can provide a public method to handle the setting.
That only works if you have a reference to frmChild02 when you create frmChild01. Since you seem to have individual buttons to launch those forms, it might be more complicated. One way to handle this would be to use Events to handle the communication. Have your Mdi Parent listen for/raise events from the child forms. So, when you click the button in frmChild01 have your Mdi parent listen for that event and raise a new event called 'ButtonClickInForm1' or something similar. Have frmChild02 subscribe to that event. If there is an instance of frmChild02 it will respond to the button click and update it's label.
You need to check if ChildForm02 is already loaded. If not you need to load it before you can set its label's text property. It might look something like this:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
If MDIParent1.ChildForm2 Is Nothing OrElse MDIParent1.ChildForm2.Visible = False Then
MDIParent1.ChildForm2 = New Form2
MDIParent1.ChildForm2.MdiParent = MDIParent1
MDIParent1.ChildForm2.Text = "Window "
MDIParent1.ChildForm2.Show()
End If
MDIParent1.ChildForm2.Label1.Text = "your text here"
End Sub
You also need to declare the child forms as Public in MdiParent form so that you can access it anywhere within the solution.
Public ChildForm1 As Form1
Public ChildForm2 As Form2

how do I catch events on runtime objects

I'm creating a form with a few buttons and a combobox at runtime.
dim f as new form
(blah blah)
then the buttons acceptDescription and rejectDescription are set up...
then the combobox descriptionCombo is set up...
then...
AddHandler acceptDescription.Click, AddressOf handleAcceptedDescription
AddHandler rejectDescription.Click, AddressOf handleRejectedDescription
then I have these two methods to catch the click events... but can't figure out how to reference the other runtime generated controls. (combobox if accepted, form if rejected)
Private Sub handleAcceptedDescription(ByVal sender As System.Object, ByVal e As System.EventArgs)
'stub
'will need to reference the chosen combobox value here
dim acceptedDescription as string = descriptionCombo.selectedValue .tostring
End Sub
Private Sub handleRejectedDescription(ByVal sender As System.Object, ByVal e As System.EventArgs)
'I want to close the runtime created form here, but can't reference it
f.close()
'and return user to main form
Me.Focus()
End Sub
If the code for generating the form is in your main form, then declare the Form variable at the class level of the main form class so you can access it from the event handlers. Same goes for your combobox and text field- you need to make sure the variables are declared outside the scope of the handlers so you can reference them within the handlers.
Why can't you reference it? Just save it as a module/form-level variable and you're set.
In order to avoid global definitions, the best answer is
Private Sub handleRejectedDescription(ByVal sender As System.Object, ByVal e As System.EventArgs)
'sender is a button in this case.
'get the button
dim b as new button
b = ctype(sender,button)
'now get the button's parent form
dim f as new form
f = ctype(b.parent, form)
'now close the form
f.close()
End Sub