Iason
Iason

Reputation: 249

Get column index after entering ContextMenuStrip_Click event

I have a simple datagridview, and I've added a context menu strip, with one choice. This context menu strip which would normally appear if you right clicked anywhere on the control, but with this code, I've made it to show only when you right click on the column header.

private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        var ht = dataGridView1.HitTest(e.X, e.Y);
        if ((ht.Type == DataGridViewHitTestType.ColumnHeader))
        {
            contextMenuStrip1.Show(MousePosition);
        }
    }
}

Goal : I would like to be able to get the column index (that I right clicked and subsequently brought the context menu up) in the showToolStripMenuItem_Click event. This is the code for this event.

private void showToolStripMenuItem_Click(object sender, EventArgs e)
{         
    var ht = dataGridView1.HitTest(Cursor.Position.X, Cursor.Position.Y);
    DataGridViewCellMouseEventArgs args = new       
        DataGridViewCellMouseEventArgs(ht.ColumnIndex, 0, 0, 0, new 
        MouseEventArgs(System.Windows.Forms.MouseButtons.Right, 0, 0, 0, 0));
    dataGridView1_ColumnHeaderMouseClick(null, args);
}

Unfortunately the showToolStripMenuItem_Click event has EventArgs, instead of DataGridViewCellMouseEventArgs, in which case it would be easy to get the column index: e.ColumnIndex.

What you see in the second function is I've tried to instantiate a DataGridViewCellMouseEventArgs class and use it to get my index, unfortunately it the e.ColumnIndex property here always returns -1.

How can I go about this?

Upvotes: 0

Views: 499

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125187

You can use CellContextMenuStripNeeded event of DataGridView.

Create a ContextMenuStrip and then handle CellContextMenuStripNeeded event of DataGridView and check if this is the column header, show context menu.

There you can detect the row index and column index using e.RowIndex and e.ColumnIndex.

Code

private void dataGridView1_CellContextMenuStripNeeded(object sender, 
    DataGridViewCellContextMenuStripNeededEventArgs e)
{
    //Check if this is column header
    if (e.RowIndex == -1)
    {
        //Show the context menu
        e.ContextMenuStrip = this.contextMenuStrip1;

        //e.ColumnIndex is the column than you right clicked on it.
    }
}

Upvotes: 3

Related Questions