winforms的datagridview内设置右键菜单,并删除指定一行,之后序列号改变

发布时间 2023-10-27 11:51:27作者: 时而有风

一、编辑右键菜单

  1、在工具箱中拖入一个contextMenuStrip控件;

  2、编辑contextMenuStrip控件,在控件内添加想要的选项,在此添加“删除”选项;

  3、(可选项)绑定DataGridView和新增的contextMenuStrip1,选中DataGridView,属性,contextMenuStrip中选择下拉:contextMenuStrip1。

二、实现在某一行点击右键弹出菜单,并选中该行

  实现DataGridView的CellMouseDown事件:右键属性中找到事件,双击CellMouseDown,编写点击事件;

private void DataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.Button != MouseButtons.Right)
    {
        return;
    }

    if (e.RowIndex < 0)
    {
        return;
    }

    //若行已是选中状态就不再进行设置
    if (DataGridView.Rows[e.RowIndex].Selected == false)
    {
        DataGridView.ClearSelection();
        DataGridView.Rows[e.RowIndex].Selected = true;
    }

    //只选中一行时设置活动单元
    if (DataGridView.SelectedRows.Count == 1)
    {
        DataGridView.CurrentCell = DataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex];
    }

    //弹出操作菜单
    contextMenuStrip1.Show(MousePosition.X, MousePosition.Y);
}

三、实现删除事件

  双击contextMenuStrip控件内的删除选项,编写点击事件:

private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
{
    var currentCellRow = DataGridView.CurrentCell.RowIndex;
    //从下一行开始改序号
    for (var i = currentCellRow + 1; i < DataGridView.RowCount; i++)
    {
        DataGridView[0, i].Value = (Convert.ToInt32(DataGridView[0, i].Value) - 1).ToString();
    }

    DataGridView.Rows.RemoveAt(currentCellRow);
}

  删除前:

  删除后