2011-03-09 39 views

回答

1

是的,你需要處理MouseDown事件爲您的DataGridView,然後使用的HitTest方法返回的行和/或列索引爲給定的座標。

例如:

private void dataGridView1_MouseDown(object sender, MouseEventArgs e) 
{ 
    if (e.Button == MouseButtons.Right) 
    { 
     DataGridView.HitTestInfo hit = dataGridView1.HitTest(e.X, e.Y); 
     if (hit.Type == DataGridViewHitTestType.Cell) 
     { 
      Console.WriteLine(hit.RowIndex); 
     } 
    } 
} 
0

我更改了CellContextMenuStripNeeded事件的選擇,然後使用SelectedRows成員找到它。

private void dataGridView_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e) 
{ 
    var Dgv = sender as DataGridView; 
    if (Dgv != null) 
    { 
     // Change the selection to reflect the right-click 
     Dgv.ClearSelection(); 
     Dgv.Rows[e.RowIndex].Selected = true; 
    } 
} 

private void myToolStripMenuItem_Click(object sender, EventArgs e) 
{ 
    // Now pick up the selection as we know this is the row we right-clicked on 
    if (dataGridView.SelectedRows.Count > 0) 
    { 
     DoSomethingAmazing(dataGridView.SelectedRows[0]); 
    } 
} 

這也有突出顯示您點擊的行的預期效果。