开发者

How to add ContextMenu in a particular DataGridViewCell? (C# winforms)

I'm trying to add a ContextMenu in a particular cell of a DataGridView. Like the image below:

How to add ContextMenu in a particular DataGridViewCell? (C# winforms)

I found it very hard to do, but I did a it in a TextBox control using the below code:

private void Form1_Load(object sender, EventArgs e)
{
    foreach (Control control in this.Controls)
    {
        // Add KeyDown event to each control in the form.
        control.KeyDown += new KeyEventHandler(control_KeyDown);            
    }
}

private void control_KeyDown(object sender, KeyEventArgs e)
{
    Control ctrl = (Control)sender;
    if (e.KeyData == Keys.F1) // Check if F1 is being pressed.
    {
        if (ctrl.GetType() == typeOf(TextBox)) // Check if the control is a TextBox
        {
            ToolStripControlHost lblInfo;
            label1.Text = "This context menu is for TextBoxes.";
            lblInfo = new ToolStripControlHost(label1); // some Label 
            contextMenuStrip1.Items.Add(lblInfo);
            contextMenuStrip1.Show(ctrl, 0, 25); // Popups the contextMenu just below the textBox control.
        }
    }
}

I just don't know how to do it in a particular cell of a DataGridView. I tried exp开发者_运维百科erimenting on this code:

if (ctrl.GetType() == typeOf(DataGridView)) // Check if the control is a DataGridView
{
    DataGridViewCell testCell = dataGridView1[dataGridView1.CurrentCell.ColumnIndex, dataGridView1.CurrentRow.Index]; // Returns DataGridViewCell type

    ToolStripControlHost lblInfo;
    label1.Text = "test";
    lblInfo = new ToolStripControlHost(label1); // some Label 
    contextMenuStrip1.Items.Add(lblInfo);
    contextMenuStrip1.Show(testCell, 0, 25);
}

But i think ContextMenu only accepts a Control type on its first argument, and I got this exception:

cannot convert from 'System.Windows.Forms.DataGridViewCell' to 'System.Windows.Forms.Control'   

Are there any workaround on this? Please advice me what to do.. thanks in advance.


Attach on DataGridView MouseDown event

private void _dgwMain_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
         DataGridView.HitTestInfo info = _dgwMain.HitTest(e.X, e.Y);
         //now you can use info.RowIndex and info.CellIndex (not sure for porporty          
         //name) to generate menu you want
    }
}


Instead of opening the menu using the Cell, pass it a reference to the gridview and set the relative coordinates of the cell based on the gridview.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜