【问题标题】:How to move two Datagridview columns together如何将两个 Datagridview 列一起移动
【发布时间】:2021-01-22 23:15:06
【问题描述】:

我有一个datagridview,我允许用户对列重新排序。

但是,当用户将列移动到另一个位置时,我希望相邻的列 (visibility = false) 随之移动。

我尝试在 ColumnDisplayIndexChanged 事件中通过设置相邻列的 displayindex 来实现,但是,

我收到以下错误:

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

【问题讨论】:

  • 如果列不可见,为什么要移动它?
  • 这是一个可怕的 hack;有人请提出一个合适的解决方案,所以我可以删除它:using (Timer t = new Timer()) { t.Tick += (ss, ee) => dataGridView1.Columns[col + 1].DisplayIndex = dcol + 1; }; - 当然,您需要计算正确的数字..
  • 我在同一项目的两列中都有(不同的)数据(第一个是金额,第二个是 ID)。因此,当用户移动第一列时,第二列应该随之而来。 2nd 在某些情况下也可以显示。
  • 是否应该将计时器 hack 放入 ColumnDisplayIndexChanged 中?
  • 最后如前所述,“更改”“INVISIBLE”列的“DISPLAY INDEX”确实没有任何意义。如果您想让用户“看到”不可见的列,那么我认为当用户指示他们想要“看到”的不可见列时,更容易确定哪个“显示索引”用于哪个列。处理这些无形的索引似乎是一种浪费。您必须记住,基本订单永远不会改变。代码只是在处理用户看到的东西,或者在这种情况下甚至是他们看不到的东西。

标签: c# datagridview datagridviewcolumn


【解决方案1】:

尽管可能没有其他人感兴趣,但我还是发布了我的解决方案。 顺便说一句,为了不“破坏”对,仅当仅显示 Amount 列时才允许移动列。选中复选框时会显示 ID 列。 目前,它似乎有效。欢迎任何关于可能存在的错误的 cmets。

    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;
            }
        }           
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多