Creating a context menu on a datagridview mouse

Source: Internet
Author: User

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 ));
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.