如何在DataGridView中對選擇中的Row進行滑鼠右鍵配合快顯

  • 6099
  • 0

摘要:如何在DataGridView中對選擇中的Row進行滑鼠右鍵配合快顯

當使用DataGridView時對選取Row做編輯時要先選擇後才能取得CurrentRow,如果要再配合ContentMenuStrip時預設DataGridView則不會自動幫忙選上,必需告判斷方式才能選上,以下是當滑鼠按下右鍵時在MouseDown所做事件。

DataGridView dgv = sender as DataGridView;
if (e.Button == MouseButtons.Right)
{
    DataGridView.HitTestInfo hit = dgv.HitTest(e.X, e.Y);
    if (hit.Type == DataGridViewHitTestType.Cell)
    {
        if (!dgv.Rows[hit.RowIndex].Selected)
        {
            dgv.ClearSelection();
            dgv.CurrentCell = dgv.Rows[hit.RowIndex].Cells[hit.ColumnIndex];//配合滑鼠點下所選擇該列
            dgv.Rows[hit.RowIndex].Selected = true;
        }
    }
}

 

通過這個方式就可以在DataGridView中隨按右鍵就有該筆的快顯了。