5

我有DataGridView一个表格。当我右键单击一行时,我需要程序打开一个上下文菜单。有了这个上下文菜单,我希望能够修改DataGridView.

我已经获得了上下文菜单来显示我右键单击的位置,但我不知道从这里去哪里。因为我将删除(例如)整行,所以我需要获取所述行的索引并将其设置为选中。我尝试了这个cell_clicked事件,但我无法确定是按下鼠标左键还是鼠标右键。但是对于mouse_click事件,我无法获得行索引。

这是我的代码:

public Form()
{
   ContextMenu contextMenu = new ContextMenu();

   //Fill Context Menu
   MenuItem delete = new MenuItem("Delete");
   contextMenu.MenuItems.Add(delete);
}

private void grdSchedules_MouseClick(object sender, MouseEventArgs e)
{
   if (e.Button == System.Windows.Forms.MouseButtons.Right)
   {
      contextMenu.Show(grdSchedules, new Point(e.Y, e.Y));      
      //Get rowindex here and select row          
   }
}

我试过这样:

 private void grdSchedules_CellClick(object sender, DataGridViewCellEventArgs e)
    {
       if (e.Button == System.Windows.Forms.MouseButtons.Right) //e.Button does not work here
       {
           contextMenu.Show(grdSchedules, new Point(e.Y, e.Y));                
       }
    }        
4

3 回答 3

11

我创建了一个更简单、更快的通用方法,它适用于任何数据网格。此方法允许通过右键单击选择行。将此方法添加到 DataGridViews 的“MouseDown”事件中:

    public void DataGridView_RightMouseDown_Select(object sender, MouseEventArgs e)
    {
        // If the user pressed something else than mouse right click, return
        if (e.Button != System.Windows.Forms.MouseButtons.Right) { return; }

        DataGridView dgv = (DataGridView)sender;

        // Use HitTest to resolve the row under the cursor
        int rowIndex = dgv.HitTest(e.X, e.Y).RowIndex;

        // If there was no DataGridViewRow under the cursor, return
        if (rowIndex == -1) { return; }

        // Clear all other selections before making a new selection
        dgv.ClearSelection();

        // Select the found DataGridViewRow
        dgv.Rows[rowIndex].Selected = true;
    }
于 2014-04-09T07:03:38.320 回答
1

我找到了解决方案。这是我的做法:

        private void grdSchedules_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                int currentMouseOverRow = grdSchedules.HitTest(e.X, e.Y).RowIndex;

                for (int x = 0; x < grdSchedules.Rows.Count; x++)
                {
                    if (grdSchedules.Rows[x].Index == currentMouseOverRow)
                    {
                        grdSchedules.Rows[x].Selected = true;
                    }
                    else
                    {
                        grdSchedules.Rows[x].Selected = false;
                    }                    
                }

                contextMenu.Show(grdSchedules, new Point(e.Y, e.Y));

            }
        }
于 2013-06-20T10:27:00.030 回答
0

您可以使用grdSchedules_MouseDownorgrdSchedules_MouseUp事件而不是grdSchedules_MouseClickor grdSchedules_CellClick

于 2014-03-22T01:51:36.637 回答