You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将DataGridView行拖放后的结果保存至数据库

解决DataGridView行拖放后位置持久化到数据库的问题

1. 给数据库表添加排序字段

首先在ustroystva表中新增一个整数类型字段,比如SortOrder,用来存储每行的排序优先级——值越小,行在DataGridView中越靠前。

2. 修改数据加载逻辑,按排序字段排序

加载数据时,通过SortOrder升序查询,确保程序重启后行按上次保存的顺序显示:

command = new SqlCommand("select * from ustroystva order by SortOrder asc", connection);
adapter.SelectCommand = command;
table.Clear();
adapter.Fill(table);
dataGridView1.DataSource = table;
dt = table;

3. 拖放完成后更新排序值并保存到数据库

在dataGridView1_MouseUp方法中,行移动完成后遍历所有行,更新它们的SortOrder值,再同步到数据库:
修改后的完整MouseUp方法:

int dragRow = -1;
Label dragLabel = null;

private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.ColumnIndex < 0 || e.RowIndex < 0) return;
    dragRow = e.RowIndex;
    if (dragLabel == null) dragLabel = new Label();
    dragLabel.Text = dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString();
    dragLabel.Parent = dataGridView1;
    dragLabel.Location = e.Location;
}

private void dataGridView1_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left && dragLabel != null)
    {
        dragLabel.Location = e.Location;
        dataGridView1.ClearSelection();
    }
}

private void dataGridView1_MouseUp(object sender, MouseEventArgs e)
{
    var hit = dataGridView1.HitTest(e.X, e.Y);
    int dropRow = -1;
    if (hit.Type != DataGridViewHitTestType.None)
    {
        dropRow = hit.RowIndex;
        if (dragRow >= 0 )
        {
            int tgtRow = dropRow + (dragRow > dropRow ? 1 : 0);
            if (tgtRow != dragRow)
            {
                DataRow dtRow = DT.Rows[dragRow];
                DataRow newRow = DT.NewRow();
                newRow.ItemArray = DT.Rows[dragRow].ItemArray;

                DT.Rows.Remove(dtRow);
                DT.Rows.InsertAt(newRow, tgtRow);
                dataGridView1.Refresh();
                dataGridView1.Rows[tgtRow].Selected = true;

                // 更新所有行的SortOrder值
                for (int i = 0; i < DT.Rows.Count; i++)
                {
                    DT.Rows[i]["SortOrder"] = i;
                }
                // 保存到数据库
                adapter.Update(DT);
            }
        }
    }
    else  
    { 
        dataGridView1.Rows[dragRow].Selected = true; // 修正原代码笔误,将dataGridView2改为dataGridView1
    }

    if (dragLabel != null)
    {
        dragLabel.Dispose();
        dragLabel = null;
    }
}

4. 初始化已有数据的排序值

如果表中已有数据,需要先批量设置SortOrder初始值,比如在SQL Server中执行:

UPDATE ustroystva SET SortOrder = ROW_NUMBER() OVER (ORDER BY (SELECT NULL))

(如果是其他数据库,可调整为对应语法生成连续排序值)

5. 新增行时的排序处理

新增行时,默认将其SortOrder设为当前最大排序值+1,确保放在列表末尾:

DataRow newRow = DT.NewRow();
// 给其他字段赋值
newRow["SortOrder"] = DT.Rows.Count;
DT.Rows.Add(newRow);
adapter.Update(DT);

内容的提问来源于stack exchange,提问作者John B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 01:57:33