0
votes

I have 3 listboxes and on MouseDown event i want them to show same context menu but there items would differ on every different listbox click. For example:

- contextMenu when clicked on :listBox1 
    *  should show: {Edit,Add Items}
- contextMenu when clicked on :listBox2
    *  should show: {Remove, Add Price}
- contextMenu when clicked on :listBox3
    *  should show: {something, Remove}

Following is the code i am using for listBox1:

    private void MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            listBx_1.SelectedIndex = listBx_1.IndexFromPoint(e.Location);
            if (listBx_1.SelectedIndex != -1)
            {
                listboxContextMenu_Opening();
            }
        }
    }

    private void listboxContextMenu_Opening()
    {
        listboxContextMenu.Items.Clear();
        listboxContextMenu.Items.Add("Edit");
        listboxContextMenu.Items.Add("Add Items");
    }

Now i want listBox2 and listBox3 context menu(same menu for all three listBoxes) items to be added using MouseDown event , How could i achieve that? Suggestions are Welcomed!!

1
Why do they all need to be the same menu? You clearly have three different menus, so it makes sense to give each ListBox its own custom menu. - Brian Kintz
Ok lets consider i have three different contextMenu for them now if i want same MouseDown event(defined above) to be called on three different listBox click. then how should change my code in MouseDown event?? - Sadiq
You would just create three individual MouseDown Event Handlers and assign one to each ListBox - Brian Kintz

1 Answers

1
votes

It is much better to create 3 separate listbox ContextMenus. That way you won't need to watch for MouseDown.

But you can achieve this by dynamically editing their ContextMenu on MouseDown.

Create a ContextMenu with all the items and have the following in your MouseDown. Then assign all their MouseDown events to MouseDown.

private void MouseDown(object sender, MouseEventArgs e)
{
    ListBox l = (ListBox) sender;
    if (e.Button == MouseButtons.Right)
    {
        l.SelectedIndex = l.IndexFromPoint(e.Location);
        if (l.SelectedIndex != -1)
        {
            if (l.Name == "listBox1")
            {
                listboxContextMenu.Items.Clear();
                listboxContextMenu.Items.Add("Edit");
                listboxContextMenu.Items.Add("Add Items");
            }
            else if(l.Name = "listBox2")//etc
        }
    }
}