简体   繁体   中英

Is it possible to add ComboBox as ContextMenu item in DataGridView WindowsForms C#?

![enter image description here][1]I am trying to add a combobox to ContextMenu on a datagrid when a user right clicks, the menu will pop up. It should show exit and assign to bankID menu options where the bank ID is a combobox dropdown. I did some online search but couldn't find anything close which makes me wonder, it is even possible to do that. I created a mockup image of what I'm trying to do with some code. If anyone has done something similar and share with me, I would really appreciate it. Thanks.

    private ContextMenu menuOpp = new ContextMenu();
    private ComboBox cmbAssign = new ComboBox();
    private int currentMouseOverRow;

    private void dataGridView2_MouseClick(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            menuOpp.Name = "Exit";
            menuOpp.MenuItems.Add("Exit", new EventHandler(menuItem_Click));
            cmbAssign.Items.Add("assign");

            dataGridView2.ContextMenu = menuOpp;

            currentMouseOverRow = dataGridView2.HitTest(e.X, e.Y).RowIndex;

            menuOpp.Show(dataGridView2, new Point(e.X, e.Y));
        }
    }

I was able to resolve this myself. I created a ContextMenuStrip, added a MenuItem with sub ComboBox item, populated the ComboBox on ToolStripMenuItem Click event. Then assigned ContextMenuStrip object to its ContextMenuStrip property. After assigning the ContextMenuStrip object to a control, the contextual menu displayed as user right click.

private void InitializeComponent()
{
    System.Windows.Forms.ContextMenuStrip Context =
            new System.Windows.Forms.ContextMenuStrip();

    ToolStripMenuItem mnuAssign = new ToolStripMenuItem("Assign");

    Context.Items.Add(mnuAssign);
    ContextMenuStrip = context;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM