ToolStripControlHost defaults to (0,0) location when adding to a ContextMenuStrip

243 Views Asked by At

This question builds off of this question. What I am doing is attempting to add a DateTimePicker control to a contextmenustrip using ToolStripControlHost. What is odd is the first time I select it in the contextmenu it shows at the location (0,0)

First time

When I hover back to the option again, it displays at the right location.

enter image description here I can't find where its setting the location. I've tried setting the location of the control being added but does nothing.

    public SampleProgram()
    {
        IntializeComponent();
        DateTimePicker sampleDatePicker = new DateTimePicker();
        sampleDatePicker.TextChanged += new EventHandler(dateTimePicker_OnTextChange);
        sampleDatePicker.Format = DateTimePickerFormat.Short;
        datagridview1.Controls.Add(sampleDatePicker);
    }

    private void datagridview1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
    {
        if (e.ColumnIndex != -1 && e.RowIndex != -1 && e.Button == MouseButtons.Right)
        {
            datagridview1.ContextMenuStrip = new ContextMenuStrip();
            datagirdview1.ContextMenuStrip.Items.Clear();

            Get_Alphabetical_User_Groups(datagridview1.ContextMenuStrip, SampleContextMenu_Action);
            datagridview1.ContextMenuStrip.Items.Add(new ToolStripSeparator());

            GetStatusList(datagridview1.ContextMenuStrip, false, SampleContextMenu_Action);
            datagridview1.ContextMenuStrip.Items.Add(new ToolStripSeparator());

            GetDatePicker(datagridview1.ContextMenuStrip, SampleContextMenu_Action);
            datagridview1.ContextMenuStrip.Items.Add("Copy Cell Data", Resources.blank, SampleContextMenu_Action);
            datagridview1.ContextMenuStrip.Show(Cursor.Position.X, Cursor.Position.Y);
        }
    }

    private void GetDatePicker(ContextMenuStrip dateMenu, EventHandler MenuOption_Click_Handler)
    {
        Point mouseloc = Cursor.Position;
        sampleDatePicker.Location = mouseloc;
        var datePicker = new ToolStripControlHost(sampleDatePicker);
        datagridview1.ContextMenuStrip.Items.Add(new ToolStripMenuItem("Set Followup Date to", Resources.calendar_edit, datePicker));
    }

Any help is much appreciated!

1

There are 1 best solutions below

0
On BEST ANSWER

Don't add the control to the DataGridView's Control collection. It doesn't belong there:

// datagridview1.Controls.Add(sampleDatePicker);