连续移动datagridview某行

本文介绍了一种在DataGridView中实现行上移和下移的方法。通过复制当前选中行并将其插入到目标位置,然后删除原始行,实现了行的平滑移动。此方法适用于需要调整数据表格中行顺序的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

连续移动datagridview某行
        /// <summary>
        /// 下移
        /// </summary>
        private void btnDown_Click(object sender, EventArgs e)
        {
            if (dtCopy == null)
                return;

            int currentRow = dataGridView1.CurrentCell.RowIndex;
            if (currentRow == dtCopy.Rows.Count - 1 || currentRow == -1)
            {
                return;
            }

            //复制选中行到新行中
            DataRow tempRow = dtCopy.NewRow();
            for (int i = 0; i < dtCopy.Columns.Count; i++)
            {
                tempRow[i] = dtCopy.Rows[currentRow][i];
            }

            dtCopy.Rows.InsertAt(tempRow, currentRow + 2);
            dtCopy.Rows.RemoveAt(currentRow);
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dataGridView1.Rows[currentRow + 1].Selected = true;

            dataGridView1.CurrentCell = dataGridView1.Rows[currentRow + 1].Cells[0];//设定当前行
        }
        /// <summary>
        /// 上移
        /// </summary>
        private void btnUp_Click(object sender, EventArgs e)
        {
            if (dtCopy == null)
                return;

            int currentRow = dataGridView1.CurrentCell.RowIndex;
            if (dataGridView1.CurrentRow.Index <= 0)
            {
                return;
            }

            //复制选中行到新行中
            DataRow tempRow = dtCopy.NewRow();
            for (int i = 0; i < dtCopy.Columns.Count; i++)
            {
                tempRow[i] = dtCopy.Rows[currentRow][i];
            }

            dtCopy.Rows.InsertAt(tempRow, currentRow - 1);
            dtCopy.Rows.RemoveAt(currentRow + 1);
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dataGridView1.Rows[currentRow - 1].Selected = true;

            dataGridView1.CurrentCell = dataGridView1.Rows[currentRow - 1].Cells[0];//设定当前行

        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值