是否可以使用C#在datagridview中显示项目范围选择的上下文菜单

时间:2016-08-02 06:44:41

标签: c#-4.0 datagridview contextmenu

是否可以使用c#在datagridview中显示项目范围选择的上下文菜单。通常,我们可以在选择任何项目时显示上下文菜单,然后右键单击鼠标。 同样,我们可以在Windows应用程序的datagridview中为项目范围(两个或更多项目选择)显示相同的上下文菜单吗?

感谢。

1 个答案:

答案 0 :(得分:0)

这就是我的工作。假设您的DataGridView(DGv)为dataGridView1且ContextMenuStrip为cms

首先设置MultiSelect& SelectionModeDGv& true的{​​{1}}属性分别为FullRowSelect

//capturing current mouse coordinate to diplay menu where the mouse pointer is. 
//MouseX & MouseY is an int variable and it's global to this class.
private void dataGridView1_MouseDown(object sender, MouseEventArgs e){
    MouseX = e.X;
    MouseY = e.Y;
}

//Avoid row selection when Right Click. This is optional you can ignore this one if you want to select the Row on Right Click
private void dataGridView1_MouseUp(object sender, MouseEventArgs e){
    if (e.Button == MouseButtons.Right){
        DataGridView.HitTestInfo hti = dataGridView1.HitTest(e.X, e.Y);
        dataGridView1.Rows[hti.RowIndex].Selected = false;
    }
}

//Time to show the menu.
private void dataGridView2_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e){
    if(e.Button == MouseButtons.Right && e.RowIndex > -1){
            contextMenuStrip1.Items.Clear(); //Since I am adding the menu items dynamically. I am clearing the previous menu to avoid repeatition. Ignore this step if your menu is static/predefined
            foreach(DataGridViewRow gr in dataGridView1.Rows){
                if(gr.Selected){
                 //if row is selected, I adding the Value of the First Cell as Menu Item
                 cms.Items.Add(gr.Cells[0].Value.ToString());
                 cms.Items.Add("-"); //adding menu separator
                }
            }
            cms.Show(dataGridView1, new System.Drawing.Point(MouseX, MouseY)); //this will add First Cell Value of all selected Rows as menu item and display the Context Menu
        }
    }

我希望这足以满足你的要求。