Search code examples
c#winformslistviewlistviewitemcontextmenustrip

Is there a way to assign a ContextMenuStrip to a ListViewItem?


I want to assign the same ContextMenuStrip to all of the ListViewItems on a form. These ListViewItems are created dynamically.

Unfortunately, it seems ListViewItems do not have a ContextMenuStrip property that can be assigned to (of course, the ListView itself does).

Will I have to just assign the ContextMenuStrip to the ListView and then, based on the ListView's currently selected item, proceed from there?


Solution

  • private void listView1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            var hitTestInfo = listView1.HitTest(e.X, e.Y);
            if (hitTestInfo.Item != null)
            {
                var loc = e.Location;
                loc.Offset(listView1.Location);
    
                // Adjust context menu (or it's contents) based on hitTestInfo details
                this.contextMenuStrip2.Show(this, loc);
            }
        }
    }