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