1. 程式人生 > >DataGridView右鍵單擊彈出選單並選中行

DataGridView右鍵單擊彈出選單並選中行

要求:
datagridview右鍵單擊,彈出選單。如果右鍵單擊處的行是被選中的,則對這些選中的行進行操作;如果右鍵單擊處的行不是被選中的,則清除所有選中的行,並選中當前行,然後進行操作。

程式碼:

        private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (!dataGridView1.Rows[e.RowIndex].Selected)
                {
                    if (e.RowIndex >= 0)
                    {
                        dataGridView1.ClearSelection();
                        dataGridView1.Rows[e.RowIndex].Selected = true;
                        contextMenuStrip2.Show(MousePosition.X, MousePosition.Y);
                    }
                }
                else
                {
                    contextMenuStrip2.Show(MousePosition.X, MousePosition.Y);
                }
            }
        }