ContextMenuStrip event handler at runtime - vb.net

I create Context menu at runtime depends of text in selected cell of datagridview.
Like this:
With ContextMenuStrip1
.Items.Clear()
Dim Str As String = DataGridView1.Item(1, DataGridView1.CurrentRow.Index).Value
Dim strArr() As String = Str.Split(" ")
For count As Integer = 0 To strArr.Length - 1
If strArr(count).Length > 1 Then
.Items.Add(strArr(count))
End If
Next
.Items.Add("-")
.Items.Add("Common operation ...")
.Items.Add("Second common operation ...")
AddHandler .Click, AddressOf cMenu_Click
.Show(New Point(Cursor.Position.X, Cursor.Position.Y))
End With
etc...
Then I add event handler like this:
Private Sub cMenu_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim mytext As String
mytext = (CType(sender, ContextMenuStrip).Text)
Debug.Print(mytext)
'after all...
RemoveHandler ContextMenuStrip1.Click, AddressOf cMenu_Click
End Sub
And as vbnet beginner with this code I can't get text of fired menu item in event handler.
So please help to get it.

Each menu item needs the handler.
Try it this way (updated with adding a shortcut key):
For count As Integer = 0 To strArr.Length - 1
If strArr(count).Length > 1 Then
Dim newMenu As New ToolStripMenuItem(strArr(count), _
Nothing, AddressOf cMenu_Click)
newMenu.ShortcutKeys = Keys.Control Or Keys.C
.Items.Add(newMenu)
End If
Next
Your click method should be changed to handle a ToolStripMenuItem instead:
Private Sub cMenu_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim mytext As String
mytext = DirectCast(sender, ToolStripMenuItem).Text
Debug.Print(mytext)
End Sub

Add a handler (pointing to the same method) for the Click Event of all of the child Items of your ContextMenuStrip. Then in your method cast it as a ToolStripMenuItem or MenuItem class (whatever you're using) to find the text of the clicked item.

Related

Add click events to ToolStripTextBox in VB.NET when created in code

I am creating tabs to keep track of open files. When I create them I can set their properties and add them to the list in a MenuStrip.
Before I do so I want to add a click event function. Since this is in a function and will be run multiple times, I need to have a dynamic way to do add these event handlers. I cannot write this:
Private Sub ToolStripTextBox1_Click(sender As Object, e As EventArgs) Handles ToolStripTextBox1.Click
' ...
End Sub
If I do this I can only name them all one name. I want to be able to add a click event that applies to them separately as individual items.
UPDATE:
Dim textFile As ToolStripTextBox = New ToolStripTextBox("textFile")
FileList.Items.Add(textFile)
textFile.Text = filename
textFile.ReadOnly = True
textFile.BackColor = Color.FromArgb(61, 61, 61)
textFile.ForeColor = Color.White
This is the creation and personalization code. Though when you guys suggested AddButton_Click() Handles AddButton.Click It doesn't work because AddButton isn't an actual button
You can keep track of the items, add add and remove click handlers with the following code
Private FileList As New List(Of ToolStripItem)()
' put this code where you add an item
Dim filename = "whatever"
Dim textFile As ToolStripTextBox = New ToolStripTextBox(filename)
textFile.Text = filename
textFile.ReadOnly = True
textFile.BackColor = Color.FromArgb(61, 61, 61)
textFile.ForeColor = Color.White
add(textFile)
Private Sub clickHandler(sender As Object, e As EventArgs)
Dim item = DirectCast(sender, ToolStripItem)
MessageBox.Show(item.Text)
End Sub
Private Sub add(textFile As ToolStripItem)
FileList.Add(textFile) ' Since I don't know what FileList is, I ued List
AddHandler textFile.Click, AddressOf clickHandler
OpenProjectToolStripMenuItem.DropDownItems.Add(textFile) ' add to whatever menu item you normally do
End Sub
Private Sub remove(textFile As ToolStripItem)
FileList.Remove(textFile)
RemoveHandler textFile.Click, AddressOf clickHandler
OpenProjectToolStripMenuItem.DropDownItems.Remove(textFile)
End Sub
The sample click event in your code includes this:
sender As Object
You can re-use this one event handler, because whichever menu item is clicked will be the sender. So you do something like this:
Private Sub ToolStripTextBox1_Click(sender As Object, e As EventArgs) Handles ToolStripTextBox1.Click
Dim menuItem = DirectCast(sender, ToolStripMenuItem)
If menuItem Is Nothing Then Return
'If you need to choose different code for each item:
Select Case menuItem.name
Case "some item"
Case "some other item"
End Select
End Sub
And you can connect your dynamic toolstrip items to this method using AddHandler:
AddHandler myMenuStrip.Click, AddressOf ToolSTripTextBox1_Click

How to get the name of a button that's clicked outside it's individual event procedure

I'm pretty new to Visual Basic so sorry if I happen to use the wrong wording.
I have a lot of small buttons on a single form, and was wondering if there was a uniform way to get the name of a button when it's clicked. Since there are so many buttons, I would like to not have to code each individual button to do what I want but instead have 1 method that gets the name of the button when its clicked, and from the name does something. I'm not sure if this is possible at all, but it would make my program much simpler.
Create only one event handler for all buttons
Private Sub Button_Click(sender As Object, e As EventArgs)
Dim button As Button = DirectCast(sender, Button)
Dim name As String = button.Name
' use name
End Sub
Then you can "attach" this handler to all buttons in the constructor
Public Sub New()
InitializeComponents()
AddHandler button1.Click, AddressOf Button_Click
AddHandler button2.Click, AddressOf Button_Click
AddHandler button3.Click, AddressOf Button_Click
' ...
End Sub
Or use "less readable", in case of big amount of controls, approach - Handles keyword
Private Sub Button_Click(sender As Object, e As EventArgs) Handles button1.Click,
button2.Click,
button3.Click,
button4.Click
' code
End Sub
Usually eventhandlers provide instance of the control which raised an event - sender
Because type of the parameter is object you need cast parameter to the type you expected and use it.
If your button naming could be done programmatically then maybe you should be creating the buttons programmatically. I had a similar problem with text boxes. here is a part of the code I used to generate them on the fly. Perhaps you could use it as a model to create buttons on the fly.
Private Class cCell
Private value As Integer
Private cellTB As TextBox
Public Sub New(ByVal idx As Integer, ByVal col As Integer, ByVal row As Integer)
value = 0
cellTB = mkTB(idx, col, row)
Form1.Controls.Add(cellTB)
End Sub
Private Function mkTB(ByVal idx As Integer, ByVal col As Integer, ByVal row As Integer)
Dim tb As New TextBox
tb.Top = Form1.cMargin + row * (Form1.cUnit + Form1.cMargin) + Int(row / 3) * Form1.cMargin * 3
tb.Left = Form1.cMargin + col * (Form1.cUnit + Form1.cMargin) + Int(col / 3) * Form1.cMargin * 3
tb.Width = Form1.cUnit
tb.Height = Form1.cUnit
tb.Name = "cellTB" & idx.ToString
tb.Text = ""
AddHandler tb.TextChanged, AddressOf cCell_TextChanged
Return tb
End Function
Private Sub cCell_TextChanged() ' change text event handler for the cells textbox
If IsNumeric(cellTB.Text) Then
If cellTB.Text > 9 Or cellTB.Text < 1 Then
cellTB.Text = ""
Else
cellTB.Font = New Font(cellTB.Font, FontStyle.Bold)
cellTB.ForeColor = Color.Black
value = cellTB.Text
trimPList()
End If
Else
cellTB.Text = ""
End If
End Sub
End Class
Private Sub mkCells()
Dim idx As Integer
Dim col As Integer
Dim row As Integer
For idx = 0 To 80
row = Int(idx / 9)
col = idx Mod 9
aCells(idx) = New cCell(idx, col, row)
Next
End Sub

Button Array - how to pass a parameter to shared handler

I have a bit of code where i have a dynamically created array or buttons with staff pictures on them, as well as the staff's name. I've added one handler to handle any button click from any of the buttons. where i am stuck is, if you look at the code below, it all works fine, and if you click any of the buttons you get the "aha" test message. but i want the name of the staff clicked on (so btnArray(i).Text) to be passed to the handler for further processing. I tried adding a ByVal parameter to the handler but that caused an error. what's the correct way to do this? As i said, the code below works for me, i just am at a loss as to how to add the extra functionality.
Dim btnArray(staffcount) As System.Windows.Forms.Button
For i As Integer = 1 To staffcount - 1
btnArray(i) = New System.Windows.Forms.Button
btnArray(i).Visible = True
btnArray(i).Width = 80
btnArray(i).Height = 101
btnArray(i).BackgroundImage = Image.FromFile(picloc(i))
btnArray(i).BackgroundImageLayout = ImageLayout.Stretch
btnArray(i).Text = staffname(i)
Dim who As String
who = btnArray(i).Text
AddHandler btnArray(i).Click, AddressOf Me.theButton_Click
btnArray(i).ForeColor = Color.White
btnArray(i).TextAlign = ContentAlignment.BottomCenter
Dim fnt As Font
fnt = btnArray(i).Font
btnArray(i).Font = New Font(fnt.Name, 10, FontStyle.Bold)
FlowLayoutPanel1.Controls.Add(btnArray(i))
Next i
End Sub
Private Sub theButton_Click()
MsgBox("aha")
End Sub
First, correct the signature of your shared handler.
Private Sub theButton_Click(sender As Object, e As EventArgs)
End Sub
Once that is done getting the text of the button clicked is a simple matter.
Private Sub theButton_Click(sender As Object, e As EventArgs)
Dim textOfButtonClicked As String = DirectCast(sender, Button).Text
MessageBox.Show(textOfButtonClicked)
End Sub
The sender is the button that was clicked. Since signatures use objects for the sender the DirectCast 'changes' it to button and you then can access the .Text property of the button.
If there are more manipulations you want to perform on the clicked button you could do it this way
Private Sub theButton_Click(sender As Object, e As EventArgs)
Dim whBtn As Button = DirectCast(sender, Button) ' get reference to button clicked
Dim textOfButtonClicked As String = whBtn.Text
MessageBox.Show(textOfButtonClicked)
'e.g. change the color
whBtn.BackColor = Color.LightYellow
End Sub

How do I add then select the dynamic control I just added

I've got an application in VB.net which adds a picturebox to the selected mouse position within another picturebox control. I need to create a click event to select that new picturebox so I can drag it and drop it to a new location in the event that the first one was wrong or use a keypress event, those events I will code later, but I can not figure out how to select ANY of the dynamic controls.
In vb6 there was a way to select an index of the control, but there is no such animal in VB.net.
I've tried control groups, but for some reason I'm not getting results from them.
Here is the code I have so far
Private Sub PictureBox1_Click(sender As System.Object,
e As System.EventArgs) Handles PictureBox1.Click
Dim pb As New PictureBox
pb.BackColor = Color.Blue
Me.PictureBox1.Controls.Add(pb)
pb.Size = New Size(64, 110)
pb.Location = New Point(Cursor.Position.X - 64, Cursor.Position.Y - 110)
pb.Visible = True
End Sub
What in the name of all good things am I doing wrong here?
You need to write a generic event handler before time, using the sender parameter to refer to the object that raised the event.
Private Sub PictureBoxes_Click(sender As Object, e As EventArgs)
Dim pb = DirectCast(sender, PictureBox)
'Use pb here.
End Sub
When you create your control at run time, use an AddHandler statement to attach the method to the event.
Dim pb As New PictureBox
AddHandler pb.Click, AddressOf PictureBoxes_Click
That said, if you want to implement drag-n-drop then it's not the Click event you should be handling.
This little bit of code took some time, but I was able to do what I set out to so far...
This is before the Sub Main event
Public Class dynamicPB 'create a picturebox element which
'can be called anytime
Inherits PictureBox 'sets the type of control to a
'picturebox
Public Sub New() 'sets the function of the new box to
'default values
MyBase.BackColor = Color.AliceBlue
MyBase.BorderStyle = Windows.Forms.BorderStyle.Fixed3D
MyBase.Height = 50
MyBase.Width = 26
End Sub
End Class
in the actual main class
Private Sub <control_event> (blah...) Blah...
Dim intPosAdj_X As Integer = 13 'get an offset for the cursor
Dim intPosAdj_Y As Integer = 25
Dim newPictureBox As New dynamicPB 'sets the click of the mouse into a
'mode of drawing a new PB
With newPictureBox 'clean use of the code
AddHandler newPictureBox.Click, _
AddressOf PictureBox_Click 'establishes events for the mouse
'activity on the objects
AddHandler newPictureBox.MouseEnter, _
AddressOf PictureBox_MouseEnter
AddHandler newPictureBox.MouseLeave, _
AddressOf PictureBox_MouseLeave
pbName += 1 'gives a unique name to the
'picturebox in an "array" style
.Location = New System.Drawing.Point _
(xPos - intPosAdj_X, yPos - intPosAdj_Y) 'establish where the box goes
'and center the object on the
'mouse pointer
.Visible = True 'ensures that the box is visible
.Name = pbName 'names the new control
End With
Controls.Add(newPictureBox) 'add control to form
End Sub
Private Sub PictureBox_Click(sender As System.Object, e As System.EventArgs)
Dim dblMouseClick As Double = CType(DirectCast _
(e, System.Windows.Forms.MouseEventArgs).Button, MouseButtons) _
'make it simple to manipulate
'the event by putting the long
'code into a variable
If dblMouseClick = MouseButtons.Left Then
MsgBox("Left CLick")
ElseIf dblMouseClick = MouseButtons.Right Then
MsgBox("right click")
Else
MsgBox("Center")
End If
This actually resolves the issue of adding and being able to select the object
Thanks for all of the suggestions and help

VB.NET ComboBox results selected item

Hi I have a vb windows form application that has a ComboBox from the form1 I have some code that reads some registry and adds item results to combobox. I would like to select one of the results and run a start process. My problem is where do I put the code when item is selected then do something and how to I determine what has been selected?
My Code to query registry keys
Dim Key, Reader As RegistryKey, Y As String
Key = Registry.LocalMachine.OpenSubKey("SOFTWARE\AppStream\AppMgr\Shortcuts", False)
For Each X In Key.GetSubKeyNames
Reader = Registry.LocalMachine.OpenSubKey("SOFTWARE\AppStream\AppMgr\Shortcuts\" & X, False)
If Reader.GetValueNames().Contains("AppTitle") Then
Y = Reader.GetValue("AppTitle")
If Not ComboBox1.Items.Contains(Y) Then ComboBox1.Items.Add(Y)
End If
If i do somehting like this, it just shows a blank messagebox and I have not selected that text from combobox yet.
If ComboBox1.SelectedText Then
MessageBox.Show(ComboBox1.SelectedText())
End If
You subscribe to the SelectedIndexChanged event writing a method like this
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim comboBox As comboBox = CType(sender, comboBox)
' Caution, the event could be called also when there is nothing selected
if combBox.SelectedItem IsNot Nothing Then
Dim curValue = CType(combBox.SelectedItem, String)
'do your stuff with the selected key'
End If
End Sub
if combBox.SelectedItem IsNot Nothing Then
Dim cmbselected As String = DirectCast(DirectCast(DirectCast(DirectCast(combBox, System.Windows.Controls.ComboBox).SelectedValue, System.Object), System.Data.DataRowView).Row, System.Data.DataRow).ItemArray(0)
End If