how to activate context menu for listview item not for Column Headers

18,688

Solution 1

How about this?

private void listView1_MouseClick(object sender, MouseEventArgs e)
    {
        ListView listView = sender as ListView;
        if (e.Button == System.Windows.Forms.MouseButtons.Right)
        {
            ListViewItem item = listView.GetItemAt(e.X, e.Y);
            if (item != null)
            {
                item.Selected = true;
                contextMenuStrip1.Show(listView , e.Location);
            }
        }
    }

This sets it up so the context menu only shows if the right click happens on an item, because if the right click happens on a header or something else then item will be null. Hope it helps

Solution 2

This could be useful for you

private void listView1_MouseClick(object sender, MouseEventArgs e)
    {            
        if (e.Button == MouseButtons.Right)
        {
            if (listView1.FocusedItem.Bounds.Contains(e.Location) == true)
            {
                contextMenuStrip1.Show(Cursor.Position);
            }
        } 
    }

The "Bounds" property is a rectangle that represents the edges of the "FocusedItem" in pixels. So if the cursor is in this rectangle area when mouse right clicked then the "contextMenuStrip1" shows up.

Solution 3

You can cancel the viewing of the context menu if there are no items selected, which will be valid only if you right click an item

    /// <summary>
    /// ContextMenuStrip Opening Action
    /// </summary>
    private void listContextMenuStrip_Opening(object sender, CancelEventArgs e)
    {
        // If there are no items selected, cancel viewing the context menu
        if (connectionListView.SelectedItems.Count <= 0)
        {
            e.Cancel = true;
        }
    }
Share:
18,688
Vivekh
Author by

Vivekh

Updated on June 04, 2022

Comments

  • Vivekh
    Vivekh almost 2 years

    I am having my Listview as follows

     Header1      Header2      Header3
      Item1        Item2        Item3
      Item1        Item2        Item3
      Item1        Item2        Item3
    

    I have written a code to show context menu on clicking the list view but it is showing the Context menu on headers too. I need to display Context menu only when user clicks on Items of list view can any one help me

    This is my code I written at present

    private void listView1_MouseClick(object sender, MouseEventArgs e)
        {
            contextMenuStrip1.Show(listView1, e.Location);
        }