dataGridView控件和contextMenuStrip控件的结合使用

效果展示: 

0. 在dataGridView 控件中绑定 contextMenuStrip 控件, 设置 ContextMenuStrip
1.  设置 dataGridView 选中类型为整行选中: SelectionMode: FullRowSelect
不允许 dataGridView 一次能选择多个单元格: MultiSelect: Fale

2. 第二步再 dataGridView 控件中分别使用 CellMouseDown 事件和 MouseDown 事件
3. 在 MouseDown 事件中隐藏所有按钮,具体根据需求具情况而定

private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
{
    xiugaixues.Visible = false; //隐藏修改按钮
    shanchuxues.Visible = false; //隐藏删除按钮
}

4. CellMouseDown 事件中显示所有按钮,具体更具需求情况而定

private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.RowIndex > -1)
    {
        //选中我当前右键的行
        this.dataGridView1.Rows[e.RowIndex].Selected = true;
        xiugaixues.Visible = true;
        shanchuxues.Visible = true;
    }
}

5. 当点击鼠标右键编辑按钮时: 获取这一行的id

private void xiugaixues_Click(object sender, EventArgs e)
{
    string student = this.dataGridView1.SelectedRows[0].Cells["StudentId"].Value.ToString();
    GetPudateInfos(student); //将id传入sqlhelper 中进行查询
}

 

posted @ 2024-06-13 13:02  龙卷风吹毁停车场  阅读(154)  评论(0)    收藏  举报