简体   繁体   中英

How to get the column index of a DataGridView through click of ContextMenu in Winforms?

I have a DataGridView with 9 columns. I have added the same ContextMenuStrip for all the column headers.

dataGridView.Columns[i].HeaderCell.ContextMenuStrip = myContextMenuStrip;

myContextMenuStrip contains a single item named Hide Column.

Now, I have an event handler for hidecolumnClick event and I want to find out which column header has been clicked inside the event handler? Is there a way to do this?

Subscribe to the DataGridView.CellMouseDown event. In the event handler, store the column index or show the required context menu.

Sample Code:

void datagridview1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        //get the RowIndex or ColumnIndex from the event argument
    }
}

Hi I have come up with another soution if u want to use the same object of ContextMenu for all the header. check it out..

Bind the CellMouseDown event on Grid-

dataGridView1.CellMouseDown += new DataGridViewCellMouseEventHandler(dataGridView1_CellMouseDown);

and in cellmousedown set the value of column clicked as below -

int columnClicked = -1;

void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
     columnClicked = e.ColumnIndex;
}

now you can access the column clicked value in context menu item clicked event as below

private void helloToolStripMenuItem_Click(object sender, EventArgs e)
{
    MessageBox.Show(columnClicked.ToString());
}

It is excepted u have assign the context menu to header already..

if you want i can give u the sample also..

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