2013-06-19 43 views
2

我在表單上有一個DataGridView。當我右鍵單擊一行時,我需要程序打開一個上下文菜單。通過這個上下文菜單,我希望能夠修改DataGridView中的數據。在mouse_click事件中選擇DataGridView中的行

我已經得到上下文菜單來顯示我右鍵單擊的位置,但我不知道從哪裏去。因爲我將刪除(例如)整行,我需要獲取所述行的索引,並將其設置爲selected。我在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));     
     } 
    }   
+0

您可以在'CellClick'中使用'MousePosition'來代替'e.X'和'e.Y'。您可能必須將座標轉換爲網格空間,但這很簡單。 – DonBoitnott

+0

這應該會幫助你:http://stackoverflow.com/questions/1718389/right-click-context-menu-for-datagrid – computer10171

+0

我得到它的工作。編輯上面的帖子,包括答案... – LeonidasFett

回答

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

      } 
     } 
0

你可能已經使用了grdSchedules_MouseDowngrdSchedules_MouseUp事件,而不是grdSchedules_MouseClickgrdSchedules_CellClick

6

我創建了一個更簡單,更快速的通用方法,它可以處理任何數據網格。該方法允許通過右鍵單擊來選擇行。將此方法添加到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; 
    }