首页 > 解决方案 > 如何将两个 Datagridview 列一起移动

问题描述

我有一个datagridview允许用户重新排序列的地方。

但是,当用户将一列移动到另一个地方时,我希望相邻的列(可见性 = false)随之移动。

我试图通过设置相邻列的 ColumnDisplayIndexChanged事件来做到这一点,但是,displayindex

我收到以下错误:

“System.InvalidOperationException:在调整列的 DisplayIndex 时无法执行此操作。”

标签: c#datagridviewdatagridviewcolumn

解决方案


即使可能没有其他人感兴趣,我也会发布我的解决方案。顺便说一句,为了不“破坏”对,仅当仅显示 Amount 列时才允许移动列。选中复选框时会显示 ID 列。目前,它似乎有效。欢迎对可能的错误提出任何意见。

    private void dataGridViewAllBatches_MouseUp(object sender, MouseEventArgs e)
    {
        for (int i = 1; i < dataGridViewAllBatches.Columns.Count; i=i+2)
        {
            if (dataGridViewAllBatches.Columns[i+1].DisplayIndex != dataGridViewAllBatches.Columns[i].DisplayIndex +1)
            {
                dataGridViewAllBatches.Columns[i + 1].DisplayIndex = dataGridViewAllBatches.Columns[i].DisplayIndex + 1;
            }
        }           
    }

推荐阅读