I have created a contextmenu (cnt_hys) and am adding items to it as program runs based on the user input in textbox1. when the user clicks button1 the contextmenu shows up and when the user clicks an item on the contextmenu strip i want to get the text of the clicked item.
I am using this code but it always returns returns the first item even if the user clicks the last item

Dim s As String = CType(sender, ContextMenuStrip).GetItemAt( _
                          CType(sender, ContextMenuStrip).DisplayRectangle.X, _
                          CType(sender, ContextMenuStrip).DisplayRectangle.Y).Text.Trim()

i got the while browsing the web i dont remember where i got it

I have also tried the following

Dim s as string = ""
Dim myItem As ToolStripMenuItem = CType(sender, ToolStripMenuItem)
Dim cms As ContextMenuStrip = CType(myItem.Owner, ContextMenuStrip)
s = cms.SourceControl.Name

so anyone knows how i can bypass this problem?
thnx in advnc

Have you tried this basic way to do it?

' Add some items
ContextMenuStrip1.Items.Add("First")
ContextMenuStrip1.Items.Add("Second")
ContextMenuStrip1.Items.Add("Third")

and when you handle the ItemClicked event:

Private Sub ContextMenuStrip1_ItemClicked(sender As Object, e As System.Windows.Forms.ToolStripItemClickedEventArgs) Handles ContextMenuStrip1.ItemClicked

    Select Case e.ClickedItem.ToString()
        Case "First"
            ' Item with text "First" selected
        Case "Second"
            ' Item with text "Second" selected
        Case "Third"
            ' Item with text "Third" selected
    End Select

End Sub

HTH

Unfortunately that method cannot be used here (at least i don't think it can) because this is actually a kind of a search program and the items of the context menu are the keyword input by the user so the text would not be known. any other way please?

the items of the context menu are the keyword input by the user so the text would not be known

That's correct. In my example I just used predefined words. But the key point is to check e.ClickedItem.ToString() which is the word user selected. This might be a better example:

Private userInput As String

Private Sub ContextMenuStrip1_ItemClicked(sender As Object, e As System.Windows.Forms.ToolStripItemClickedEventArgs) Handles ContextMenuStrip1.ItemClicked

    userInput = e.ClickedItem.ToString()

End Sub

Now the variable userInput holds the word (or text) the user selected in context menu.

HTH

This might be a better example:

Private userInput As String
     
    Private Sub ContextMenuStrip1_ItemClicked(sender As Object, e As System.Windows.Forms.ToolStripItemClickedEventArgs) Handles ContextMenuStrip1.ItemClicked
     
    userInput = e.ClickedItem.ToString()
     
    End Sub

Now the variable userInput holds the word (or text) the user selected in context menu.

Thankq Thankq Thankq it wrked :)

This question has already been answered. Start a new discussion instead.