在C#中給dataGridView的每行新增一個選單,通過右擊顯示選單
實現如圖功能:
1.新增一個contextMenuStrip到當前視窗,items為選單內容,如新增刪除
2.給dataGridView1新增右擊選單事件dataGridView1_CellMouseDown
private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e) { joid = int.Parse(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());//右擊改變索引 if (e.Button == MouseButtons.Right) { if (e.RowIndex >= 0) { //若行已是選中狀態就不再進行設定 if (dataGridView1.Rows[e.RowIndex].Selected == false) { dataGridView1.ClearSelection(); dataGridView1.Rows[e.RowIndex].Selected = true; } //只選中一行時設定活動單元格 if (dataGridView1.SelectedRows.Count == 1) { dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex]; } //彈出操作選單 contextMenuStrip1.Show(MousePosition.X, MousePosition.Y); } } }
3.對每個選單生成點選事件:更新ToolStripMenuItem_Click;刪除ToolStripMenuItem_Click