In my project I give user opportunity to add or remove a column of a DataGridView.
I do not know at runtime how many columns there might be, so in order to remove it or add one at index n , I need to know the column index clicked.
So my event handler knows that information, but a standard contextmenuitenclicked event does not.
I get around this by using a private member to keep track of the clicked column in my dataGridView1_ColumnHeaderMouseClick event handler shown in the below code.
My question is, is there a better way to do this?
Thank you for reading my post.
private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
clickedcolumn = e.ColumnIndex + 1;
Point p = new Point(e.X, e.Y);
ContextMenu cm = new ContextMenu();
cm.MenuItems.Add("Remove column " + clickedcolumn.ToString(), removeToolStripMenuItem_Click);
cm.MenuItems.Add("Add column " + clickedcolumn.ToString(), addToolStripMenuItem_Click);
cm.Show(dataGridView1, p);
}
private void removeToolStripMenuItem_Click(object sender, EventArgs e)
{
Debug.WriteLine("Remove " + clickedcolumn);
clickedcolumn = -1;
}
private void addToolStripMenuItem_Click(object sender, EventArgs e)
{
Debug.WriteLine("Add " + clickedcolumn);
clickedcolumn = -1;
}