开发者

ContextMenuStrip On RightClick, IF Items Are Selected In Listview?

I have a ContextMenuStrip attached to a list view, and it's working great,开发者_StackOverflow 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!


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.


For other people reading this thread, a nice way is to gray out the options in the menu (in Opening event) when no items are selected instead of not displaying the menu at all

if (List.SelectedItems.Count == 0)
{
    // e.Cancel=true;
    List.Enabled = false;
}
else
{
    List.Enabled = true;
}


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.


   Private Sub ListView1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListView1.MouseUp
        If e.Button = MouseButtons.Right And ListView1.SelectedItems.Count > 0 Then
            Dim cn As New ContextMenuStrip()
            cn.Items.Add("Apple")
            Me.ListView1.ContextMenuStrip = cn
            cn.Show(Control.MousePosition.X, Control.MousePosition.Y)
        End If
    End Sub
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜