C# 右键菜单 contextMenuStrip


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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM