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; }