ContextMenuStrip and Listview

  • Thread starter Thread starter Mike Horton
  • Start date Start date
M

Mike Horton

Hi There

I'm trying to use a ContextMenuStrip on a Listview and have run into a
problem that I can't seem to find the answer for. The menu itself is working
great but it's showing no matter where I right-click in the ListView. I'm
trying to get it so that it only shows when the user has right-clicked on an
actual ListItem vs empty space in the form.

I've tried putting the following code in the Opening sub for the Listview
but I still get it popping up even though the SelectedItems=0.

If lvAdmin.SelectItems.Count > 0 Then
cmsListView.Visible = True
Else
cmsListView.Visible = False
End If

Any pointers to a solution would be greatly appreciatted.
 
Hi There

I'm trying to use a ContextMenuStrip on a Listview and have run into a
problem that I can't seem to find the answer for. The menu itself is
working great but it's showing no matter where I right-click in the
ListView. I'm trying to get it so that it only shows when the user has
right-clicked on an actual ListItem vs empty space in the form.

I've tried putting the following code in the Opening sub for the Listview
but I still get it popping up even though the SelectedItems=0.

If lvAdmin.SelectItems.Count > 0 Then
cmsListView.Visible = True
Else
cmsListView.Visible = False
End If

Any pointers to a solution would be greatly appreciatted.

You will need to get the ListViewItem at 0, MousePosition.Y and see if it
is valid. You may have to tweak the '0' slightly - try 1 or 2 if 0 doesn't
work.
 
You will need to get the ListViewItem at 0, MousePosition.Y and see if it
is valid. You may have to tweak the '0' slightly - try 1 or 2 if 0 doesn't
work.

Here is an alternate solution :

First, don't use the ContextMenuStrip property of your listview
In the MouseClick event of your listview, check if the right button is
pressed and if an item is selected, then shows the contextual menu.

private void listView_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right && listView.SelectedItems.Count
== 1)
{
contextMenuStrip.Show(MousePosition);
}
}

Maybe it's not the best way to do it, but it works.
 
Thank you Jeff and neva. I will look at your solutions on Monday when I
return to work.
 
Back
Top