Right Click on columns in data grid
Hi Im trying to add right click to each one of my columns , and under
the right click im going to hide each column, I know how to hide the
column , but i want to add the right click option on each column , can
you assist me

David SmithRank #999 · 2K reputationPosted Feb 21, 2010, 5:31 PM EST
//Define different context menus for different columns
private ContextMenu contextMenuForColumn1 = new ContextMenu();
private ContextMenu contextMenuForColumn2 = new ContextMenu();
private void dataGridView_MouseUp(object sender, MouseEventArgs e)
{
// Load context menu on right mouse click
DataGridView.HitTestInfo hitTestInfo;
if (e.Button == MouseButtons.Right)
{
hitTestInfo = dataGridView2.HitTest(e.X, e.Y);
// If column is first column
if (hitTestInfo.Type == DataGridViewHitTestType.Cell && hitTestInfo.ColumnIndex == 0)
contextMenuForColumn1.Show(dataGridView2, new Point(e.X, e.Y));
// If column is second column
if (hitTestInfo.Type == DataGridViewHitTestType.Cell && hitTestInfo.ColumnIndex == 1)
contextMenuForColumn2.Show(dataGridView1, new Point(e.X, e.Y));
}
}
Raaj KumarRank #7,836 · 233 reputationPosted Feb 21, 2010, 11:22 PM EST
Try this code. Its working for me.
{
InitializeComponent();
contextMenuForColumn2.MenuItems.Add("Delete", new EventHandler(Delete));
contextMenuForColumn2.MenuItems.Add("Register", new EventHandler(Register));
}
private ContextMenu contextMenuForColumn1 = new ContextMenu();
private ContextMenu contextMenuForColumn2 = new ContextMenu();
private void dataGridView1_MouseUp(object sender, MouseEventArgs e)
{
// Load context menu on right mouse click
DataGridView.HitTestInfo hitTestInfo;
if (e.Button == MouseButtons.Right)
{
hitTestInfo = dataGridView.HitTest(e.X, e.Y);
// If column is first column
if (hitTestInfo.Type == DataGridViewHitTestType.Cell && hitTestInfo.ColumnIndex == 0)
contextMenuForColumn1.Show(dataGridView, new Point(e.X, e.Y));
// If column is second column
if (hitTestInfo.Type == DataGridViewHitTestType.Cell && hitTestInfo.ColumnIndex == 1)
contextMenuForColumn2.Show(dataGridView, new Point(e.X, e.Y));
}
}
void MakeActive(object sender, EventArgs e)
{
}
void Delete(object sender, EventArgs e)
{
}
void Register(object sender, EventArgs e)
{
}
Regards,
Raaj
kiran kumarRank #3,110 · 461 reputationPosted Feb 21, 2010, 11:48 PM EST
David SmithRank #999 · 2K reputationPosted Feb 22, 2010, 12:28 AM EST
thanks so much