【问题标题】:Cannot Set Value To FirstDisplayedScrollingRowIndex无法将值设置为 FirstDisplayedScrollingRowIndex
【发布时间】:2019-09-11 20:20:13
【问题描述】:

在调用ResetBindings 后,我试图阻止DataGridView 滚动。

在更新绑定到它的列表中的值后,我调用ResetBindings

调用ResetBindings 后,我无法为FirstDisplayedScrollingRowIndex 赋值。

请注意不会抛出异常。

这是我正在使用的代码:

int currentRowIndex = dgvStuff.FirstDisplayedScrollingRowIndex;

dgvStuff.CellEnter -= dgvStuff_CellEnter;
dgvStuff.Scroll -= dgvStuff_Scroll;
bindingSource.ResetBindings(false); // FirstDisplayedScrollingRowIndex value gets modified after this call;
dgvStuff.Scroll += dgvStuff_Scroll;
dgvStuff.CellEnter += dgvStuff_CellEnter;

dgvStuff.FirstDisplayedScrollingRowIndex = currentRowIndex; // This value is not being set;

上面的代码在CellValidating事件中为DataGridView

单步执行上述代码:

  • currentRowIndex 在第一行执行后的值为 12
  • 执行ResetBindings 导致FirstDisplayedScrollingRowIndex 保持3 的值
  • FirstDisplayedScrollingRowIndex 未在最后一行执行后设置为 12

我不确定值 3 的来源,但我知道在调用 ResetBindings 之后它会以某种方式在后台应用。

有人能帮我理解为什么我在调用ResetBindings 后无法修改FirstDisplayedScrollingRowIndex 的值吗?

https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.datagridview.firstdisplayedscrollingrowindex

【问题讨论】:

    标签: c# winforms datagridview bindingsource


    【解决方案1】:

    您需要做的就是更改DataGridView 中的CurrentCell,然后您应该能够将值设置为FirstDisplayedScrollingRowIndex

    我知道这是一个奇怪的修复,但它对我有用:

    int rowIndex = dgvStuff.CurrentCell.RowIndex;
    int columnIndex = dgvStuff.CurrentCell.ColumnIndex;
    int currentRowIndex = dgvStuff.FirstDisplayedScrollingRowIndex;
    
    dgvStuff.CellEnter -= dgvStuff_CellEnter;
    dgvStuff.Scroll -= dgvStuff_Scroll;
    bindingSource.ResetBindings(false);
    
    if (dgvStuff.RowCount > 0)
    {
        dgvStuff.CurrentCell = dgvLEDs[0, 0]; // This line alone fixes the issue;
        dgvStuff.CurrentCell = dgvLEDs[columnIndex, rowIndex]; // I added this line because I needed to specify the current cell;
    }
    
    dgvStuff.FirstDisplayedScrollingRowIndex = currentRowIndex; // This value is NOW being set;
    
    dgvStuff.Scroll += dgvStuff_Scroll;
    dgvStuff.CellEnter += dgvStuff_CellEnter;
    

    我希望这可以帮助像我这样陷入困境的任何人。祝你好运。

    【讨论】:

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