Hiding a ContextMenu (or preventing it from showing)

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
 
T

Thomas Weise

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
 
C

Claes Bergefall

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
 
G

Guest

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top