Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
    }
like image 384
Vivekh Avatar asked Mar 19 '12 12:03

Vivekh


2 Answers

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

like image 136
nick Avatar answered Oct 09 '22 20:10

nick


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.

like image 41
bakseli Avatar answered Oct 09 '22 21:10

bakseli