1.添加contextMenuStrip控件 默認命名:contextMenuStrip1
2.在要顯示的控件上,找到其ContextMenuStrip屬性,並設置其為contextMenuStrip1
比如我這邊放在 dataGridView1 控件上,就將dataGridView1的ContextMenuStrip屬性,設置為contextMenuStrip1
3.將dataGridView1的CellMouseDown事件下寫入下列代碼
//在右鍵點擊時,將當前行選中 private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Right && e.RowIndex >= 0) { if (!dataGridView1.Rows[e.RowIndex].Selected) { dataGridView1.ClearSelection(); dataGridView1.Rows[e.RowIndex].Selected = true; } contextMenuStrip1.Show(MousePosition.X, MousePosition.Y); } }
4.為ToolStripMenuItem 控件添加Click事件
private void 刪除ToolStripMenuItem_Click(object sender, EventArgs e) { //獲取當前選中行的索引t22 int selectRow = dataGridView1.CurrentRow.Index; if (selectRow < 0) return; }