Fr0z3n
Fr0z3n

Reputation: 1576

Visual C# ListView ContextMenu

I have a ListView to display Images Icons, and i need 2 different Context menu on that ListView that have to show when i Right Click inside the ListView.

This is the current Code that i have, but it is only working when i right click on a item:

private void ListView_MouseClick(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            if (ListView.GetItemAt(e.X, e.Y) is ListViewItem)
            {
                ContextMenu1.Show(Cursor.Position);
            }
            else
            {
                ContextMenu2.Show(Cursor.Position);
            }
        }
    }

What i did wrong?

Upvotes: 0

Views: 743

Answers (2)

TaW
TaW

Reputation: 54433

GetItemAt will always return a ListviewItem. You should check for null like this example from MSDN:

private void ListView_MouseDown(object sender, MouseEventArgs e)
{
   if (ListView.GetItemAt(e.X, e.Y) != null )
   {
          ContextMenu1.Show(Cursor.Position);

   }
       else
   {
          ContextMenu2.Show(Cursor.Position);
   }
}

Upvotes: 2

LarsTech
LarsTech

Reputation: 81610

Try using the MouseDown or MouseUp event instead:

listView1.MouseDown += listView1_MouseDown;

void listView1_MouseDown(object sender, MouseEventArgs e) {
  if (e.Button == MouseButtons.Right) {
    if (listView1.GetItemAt(e.X, e.Y) is ListViewItem) {
      ContextMenu1.Show(Cursor.Position);
    } else {
      ContextMenu2.Show(Cursor.Position);
    }
  }
}

The MouseClick event fires only when a ListItem is clicked.

Upvotes: 1

Related Questions