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);
}
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With