1. 程式人生 > >C# dataGridView選中一行右鍵出現選單,對資料進行操作

C# dataGridView選中一行右鍵出現選單,對資料進行操作

1.為dataGridView繫結資料,設定資料選定一行

this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;   //選中整行


2.新增contextMenuStrip控制元件並繫結dataGridView


3.設定選中一行時右鍵單擊出現選單

 //dataGridView選中一行時右鍵出現選單
        private void dataGridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (e.RowIndex >= 0)
                {
                    dataGridView1.ClearSelection();
                    dataGridView1.Rows[e.RowIndex].Selected = true;
                    dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    contextMenuStrip1.Show(MousePosition.X, MousePosition.Y);
                }
            }

        }


4.獲取選中行某一單元格的值

5.對資料進行操作