2013-05-27 47 views
8

我需要在顯示ContextMenu前右鍵單擊dataGridView來選擇一行,因爲contextMenu是row-dependendt。用鼠標右鍵選擇dataGridView中的行

我已經試過這樣:

if (e.Button == MouseButtons.Right) 
     { 

      var hti = dataGrid.HitTest(e.X, e.Y); 
      dataGrid.ClearSelection(); 
      dataGrid.Rows[hti.RowIndex].Selected = true; 
     } 

或:

private void dataGrid_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e) 
    { 
     if (e.Button == MouseButtons.Right) 
     { 
      dataGrid.Rows[e.RowIndex].Selected = true; 
      dataGrid.Focus(); 
     } 
    } 

這個工作,但是當我嘗試讀取dataGrid.Rows [CurrentRow.Index]我只看到左選擇的行點擊,而不是那些用右鍵點擊選擇。

回答

22

嘗試設置當前單元格像這樣(這將設置DataGridViewCurrentRow屬性之前的語境男子ü項目被選中):

private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e) 
    { 
     if (e.Button == MouseButtons.Right) 
     { 
      // Add this 
      dataGrid.CurrentCell = dataGrid.Rows[e.RowIndex].Cells[e.ColumnIndex]; 
      // Can leave these here - doesn't hurt 
      dataGrid.Rows[e.RowIndex].Selected = true; 
      dataGrid.Focus(); 
     } 

    } 
+0

謝謝,這個作品。 – user2396911

+0

不客氣! – Gjeltema

2

我知道這個線程是舊的,我只是想補充一點:如果你希望能夠選擇和執行的操作,在多行:您可以檢查看看你是否右鍵點擊的行已被選中。這樣DataGridview的行爲在這方面就像一個ListView。因此,右鍵單擊一行尚未選中的行:選擇此行並打開上下文菜單。右擊已經選擇的行只是給你上下文菜單,並保持選定的行按預期。

private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e) 
    { 
     if (e.RowIndex != -1 && e.ColumnIndex != -1) 
     { 
      if (e.Button == MouseButtons.Right) 
      { 
       DataGridViewRow clickedRow = (sender as DataGridView).Rows[e.RowIndex]; 
       if (!clickedRow.Selected) 
        dataGridView1.CurrentCell = clickedRow.Cells[e.ColumnIndex]; 

       var mousePosition = dataGridView1.PointToClient(Cursor.Position); 

       ContextMenu1.Show(dataGridView1, mousePosition); 
      } 
     } 
    } 
0
private void grid_listele_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e) 
    { 
     if (e.Button == MouseButtons.Right) 
     { 
      grid_listele.ClearSelection(); 
      grid_listele[e.ColumnIndex, e.RowIndex].Selected = true; 
     } 


    } 
+0

你可以添加解釋爲什麼OP的例子不工作,你做了什麼工作? – Yogesh

0
if (e.Button == System.Windows.Forms.MouseButtons.Right) 
     { 
      var hti = GridView.HitTest(e.X, e.Y); 
      GridView.ClearSelection(); 

      int index = hti.RowIndex; 

      if (index >= 0) 
      { 
       GridView.Rows[hti.RowIndex].Selected = true; 
       LockFolder_ContextMenuStrip.Show(Cursor.Position); 
      } 

     } 

這是準確的方法我猜

相關問題