1 ContextMenuStrip, multiple Textboxes

JuggaloBrotha

VB.NET Forum Moderator
Staff member
Joined
Jun 3, 2004
Messages
4,530
Location
Lansing, MI; USA
Programming Experience
10+
I have an interesting question.

I have made my own ContextMenuStrip containing:
Cut, Copy, Paste, Delete

And I have this set to all the TextBoxes on my form, so when the user clicks 'Copy' from the context menu on any of the textboxes, how do I detect which textbox the user right-clicked on?

Usually 'Sender' would be the object to cast as a textbox, but in this case 'Sender' is a ToolStripMenuItem and I don't see any useful methods or properties provided with 'e' either.

Any idea's?
 
oh wow, I forgot about that thread, I did however find another solution for this though:

VB.NET:
Option Explicit On
Option Strict On

Friend Class frmCard

    Private ReadOnly Property CurrentTextbox() As TextBox
        Get
            Return DirectCast(TextBoxContextMenuStrip.SourceControl, TextBox)
        End Get
    End Property

#Region " ToolStripMenuItem "
    Private Sub CutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CutToolStripMenuItem.Click
        With CurrentTextbox
            .Focus()
            .Cut()
        End With
    End Sub

    Private Sub CopyToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CopyToolStripMenuItem.Click
        With CurrentTextbox
            .Focus()
            .Copy()
        End With
    End Sub

    Private Sub PasteToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PasteToolStripMenuItem.Click
        With CurrentTextbox
            .Focus()
            .Paste()
        End With
    End Sub

    Private Sub DeleteToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DeleteToolStripMenuItem.Click
        With CurrentTextbox
            .Focus()
            .Text = ""
        End With
    End Sub
#End Region
End Class

Of course TextBoxContextMenuStrip is a MenuStrip containing 4 menu items (for now) the menu items are: Cut, Copy, Paste and Delete

This is thanks to kleinma on vbforums.com
 
You found the same solution, you mean? (SourceControl property). You can also follow the reference from 'sender' event parameter if you use the same handlers for more than one ContextMenuStrip. (sender is ToolStripMenuItem, its Owner is ToolStrip that can be cast to ContextMenuStrip, that has the SourceControl property)
 
Back
Top