ContextMenuStrip and Listview

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.
 
J

Jeff Gaines

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.
 
N

neva

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.
 
M

Mike Horton

Thank you Jeff and neva. I will look at your solutions on Monday when I
return to work.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top