Jul 1, 2009

C# Context Menu on ListViewItem

The problem when assigning a context menu directly to a ListView control is that the menu show everywhere on the control. This can be quite irritating if you just want it to show when you rightclick on a listviewitem. Below is example code to overcome the problem. Assign a contextmenu to the listview control and create a menuitem. In this example the listview contains a list of network host names/IPs, on rightclick it will show a context menu to browse to the c$ share of the host. I know its not the most elegant solution, but it works. Just note, the menu location offsets may need some tweaking.

       private void lvwHosts_MouseUp(object sender, MouseEventArgs e)
//Check if right clicked on a ListView Item
if ((lvwHosts.SelectedItems.Count != 0) && (e.Button == MouseButtons.Right))
//Create a new point relative to form and listview locations + offset
Point mousePoint = new Point();
mousePoint.X = this.Location.X + lvwHosts.Location.X + e.Location.X + 25;
mousePoint.Y = this.Location.Y + lvwHosts.Location.Y + e.Location.Y + 55;

//Show context menu
//Change text of current menu item to relevant path
cmnBrowse.Items[0].Text = @"Browse to \\" +
lvwHosts.SelectedItems[0].Text + @"\c$";


private void browseToCToolStripMenuItem_Click(object sender, EventArgs e)
string path = sender.ToString();
//Remove the "Browse to" substring
path = path.Remove(0, 10);
//Start explorer


Anonymous said...

Thanks for the assist. After sme experimentation, I was able to simply do the following in the MouseUp event:

if ((listView1.SelectedItems.Count != 0) && (e.Button == MouseButtons.Right))
ItemContextMenu.Show(listView1, e.Location);


g said...

I knew there must be an easier way! thanks for the post

Anonymous said...

C# create context menu