One of the projects had a requirement to create
Context menu on mouse click over a datagridview having employee
Details. The menu items may vary from column to column of the gridview.
// Define different context menus for different columns
Private contextmenu contextmenuforcolumn1 = new contextmenu ();
Private contextmenu contextmenuforcolumn2 = new contextmenu ();
Add the following line of code in the form load event:
Private void form_load (Object sender, eventargs E)
{
// Load all default values of controls
Populatedatagridview ();
// Add context mneu items
Contextmenuforcolumn1.menuitems. Add ("make active", new eventhandler (makeactive ));
Contextmenuforcolumn2.menuitems. Add ("delete", new eventhandler (delete ));
Contextmenuforcolumn2.menuitems. Add ("register", new eventhandler (Register ));
}
Add the following code to mouseup event of the gridview:
Private void datagridview_mouseup (Object sender, mouseeventargs E)
{
// Load context menu on right mouse click
Datagridview. hittestinfo;
If (E. Button = mousebuttons. Right)
{
Hittestinfo = datagridview. hittest (E. X, E. y );
// If column is first column
If (hittestinfo. type = maid. Cell & hittestinfo. columnindex = 0)
Contextmenuforcolumn1.show (datagridview, new point (E. X, E. y ));
// If column is second column
If (hittestinfo. type = maid. Cell & hittestinfo. columnindex = 1)
Contextmenuforcolumn2.show (datagridview, new point (E. X, E. y ));
}
}