Hiding a ContextMenu (or preventing it from showing)

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello,

I have a ListBox with column names to use in a report. When the user
right-clicks the ListBox, a ContextMenu is displayed with two items: Sort
Ascending and Sort Descending.

How can I display the ContextMenu only when the ListBox has a selected item?
(All I do now is just disable the menu items if the ListBox's SelectedIndex
is -1.)

Thank you,

Eric
 
Eric,

You have probably assigned the context menu to the ListBox by setting the
ListBox.Contextmenu property.
You should rather launch the context menu manually in the ListBox' MouseDown
procedure by this code line:
ContextMenu.Show(CType(sender, ListBox), New Point(e.X, e.Y))
In this way, you can control if you show the menu at all

Regards,
Thomas
 
You could handle the SelectedIndexChanged event and
add and remove the context menu as appropriate

Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
If ListBox1.SelectedIndex < 0 Then
ListBox1.ContextMenu = Nothing
Else
ListBox1.ContextMenu = MyContextMenu
End If
End Sub

/claes
 
Thank you both for your replies. They both work great.

Take care,

Eric


Thomas Weise said:
Eric,

You have probably assigned the context menu to the ListBox by setting the
ListBox.Contextmenu property.
You should rather launch the context menu manually in the ListBox' MouseDown
procedure by this code line:
ContextMenu.Show(CType(sender, ListBox), New Point(e.X, e.Y))
In this way, you can control if you show the menu at all

Regards,
Thomas
 
Back
Top