Reputation: 449
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?
Upvotes: 1
Views: 2639
Reputation: 3388
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
}
}
Upvotes: 2
Reputation: 4170
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..
Upvotes: 1