1.添加contextMenuStrip控件 默認命名:contextMenuStrip1spa
2.在要顯示的控件上,找到其ContextMenuStrip屬性,並設置其爲contextMenuStrip1code
好比我這邊放在 dataGridView1 控件上,就將dataGridView1的ContextMenuStrip屬性,設置爲contextMenuStrip1orm
3.將dataGridView1的CellMouseDown事件下寫入下列代碼blog
//在右鍵點擊時,將當前行選中 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; }