views:

17

answers:

2

I have a ContextMenuStrip attached to a list view, and it's working great, but what I'm interested in knowing is how I can have it show up only when one or more items are selected in the listview.

Thanks!

+1  A: 

For me its intuitive that if you have no items selected (or you right-click on a non-selected item), the item would get automatically selected just before you show the context menu.

If the first solution is not acceptable, I think I would try to attach the ContextMenuStrip when items get selected and detach it when they are unselected.

Grzenio
@Grzenio, The only problem (and it is very minor) is that if a user right clicks the listview's column headers, the menu still shows up. I will try to implement your second suggestion, thanks!
Soo
+2  A: 

You could use the Opening event. The event args has a Cancel property so that you can examine the state of your application and decide whether to have the menu show (by doing nothing) or prevent it from showing (by setting e.Cancel = true). However, like @Grzenio mentions, I would find it more intuitive if the item that i right-clicked on became selected automatically.

Another option would be to use the Opening event to populate the context menu with only one disabled item, with a text like (no item is selected) or so; this would inform the user about why the command is not available.

Fredrik Mörk
I used this with if(List.SelectedItems.Count == 0){e.Cancel=true;}Thanks!
Soo