2013-05-27 16 views
8

contextMenuがrow-dependendtなので、ContextMenuが表示される前に右クリックしてdataGridViewの行を選択する必要があります。dataGridViewの行を右クリックして選択します

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]私は左で選択した行のみを参照してください。

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

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

か:

私はこれ試してみました右クリックで選択したものをクリックしてください。

答えて

22

このように現在のセルを設定してみてください(DataGridViewのプロパティをcontext men U項目が選択されている):あなたが選択できるようにしたい場合は、および複数の行に、アクションを実行します:あなたが確認することができ

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

     } 

これは私がこの作品

関連する問題