How to activate a context menu for a list item not for column headings

I have a Listview as follows

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

I wrote code to show the context menu when I click on list view , but it also shows context menu on headers . I need to display the context menu only when the user clicks Items list view , can someone help me

This is my code that I have written now

 private void listView1_MouseClick(object sender, MouseEventArgs e) { contextMenuStrip1.Show(listView1, e.Location); } 
+7
source share
5 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(eX, eY); if (item != null) { item.Selected = true; contextMenuStrip1.Show(listView , e.Location); } } } 

This sets it so that the context menu shows whether it has the right to click on the element, because if the right click occurs in the header or something else, then the element will be empty. Hope this helps.

+13
source

It may 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. Therefore, if the cursor is in this area of ​​the rectangle when right-clicking, " contextMenuStrip1 " appears.

+9
source

You can cancel viewing the context menu if there are no elements that will be valid only if you right-click the element

  /// <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; } } 
+5
source

It's pretty dirty ... just using the information. Someone will probably come up with a better answer.

 private void listView1_MouseClick(object sender, MouseEventArgs e) { if ( e.Location.Y > headerHeightDefinedEarlier ) contextMenuStrip1.Show(listView1, e.Location); } 
0
source

You need to select an item when you click on it. Then you can query the selected items in the list and get the index of the selected item: listView1.SelectedItems[0].Index

 if (listView1.SelectedItems[0].Index == 0) return; 
0
source

All Articles