添加到ContextMenuStrip时ToolStripControlHost默认为(0,0)位置

时间:2018-07-19 18:03:58

标签: c# winforms datetimepicker contextmenustrip toolstripcontrolhost

此问题基于此question。我正在做的是尝试使用ToolStripControlHost将DateTimePicker控件添加到contextmenustrip。奇怪的是我第一次在上下文菜单中选择它,显示在位置(0,0)

First time

当我再次将鼠标悬停到该选项时,它会显示在正确的位置。

enter image description here 我找不到它在哪里设置位置。我试过设置要添加的控件的位置,但是什么也不做。

    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));
    }

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

不要将控件添加到DataGridView的Control集合中。它不属于那里:

// datagridview1.Controls.Add(sampleDatePicker);