当数据源改变时,我该如何防止DataGridView自动滚动?

3
我在绑定到DataGridView的数据源DataTable的“RowChanged”事件中尝试了此方法(http://brainof-dave.blogspot.com/2007/08/turning-off-auto-scrolling-in-bound.html),但是没有成功。
基本上,我有一个DataGridView,它的数据源是BindingSource。BindingSource的数据源是包含DataTable的DataView。每当一行数据发生更改时,DataGridView都会滚动回到顶部。是否有简单的解决方法?
2个回答

1

这是经过测试的代码,可以在更改数据源后恢复RowIndex。还可以恢复排序顺序和最后一个单元格的位置。语言:C# 7.0。 这是我个人编写的代码,有一些来自网络搜索的帮助。

    private void UpdateDataSource()
    {
        SuspendLayout();

        //Save last position and sort order
        DataGridView g = DataGridView1;
        Int32 idxFirstDisplayedScrollingRow = g.FirstDisplayedScrollingRowIndex;
        SortOrder dgvLastSortDirection = g.SortOrder;
        Int32 lastSortColumnPos = g.SortedColumn?.Index ?? -1;
        Int32 dgvLastCellRow = g.CurrentCell?.RowIndex ?? -1;
        Int32 dgvLastCellColumn = g.CurrentCell?.ColumnIndex ?? -1;

        //Set new datasource
        g.DataSource = myNewDataTableSource;                                                                     

        //Restore sort order, scroll row, and active cell
        g.InvokeIfRequired( o =>
        {
            if(lastSortColumnPos > -1)
            {
                DataGridViewColumn newColumn = o.Columns[lastSortColumnPos];
                switch(dgvLastSortDirection)
                {
                    case SortOrder.Ascending:
                        o.Sort(newColumn, ListSortDirection.Ascending);
                        break;
                    case SortOrder.Descending:
                        o.Sort(newColumn, ListSortDirection.Descending);
                        break;
                    case SortOrder.None:
                        //No sort
                        break;
                }
            }

            if(idxFirstDisplayedScrollingRow >= 0)
                o.FirstDisplayedScrollingRowIndex = idxFirstDisplayedScrollingRow;

            if(dgvLastCellRow>-1 && dgvLastCellColumn>-1)
                o.CurrentCell = g[dgvLastCellColumn, dgvLastCellRow];
        } );

        ResumeLayout();
    }

    public static void InvokeIfRequired<T>(this T obj, InvokeIfRequiredDelegate<T> action) where T : ISynchronizeInvoke
    {
        if (obj.InvokeRequired)
        {
            obj.Invoke(action, new Object[] { obj });
        }
        else
        {
            action(obj);
        }
    } 

1

看起来我找到了它:http://seewinapp.blogspot.com/2005/09/is-your-autoscroll-too-auto.html

我重写了 DataTable 上的 RowChanged 事件,存储了 FirstDisplayedScrollingRowIndex,使用该索引作为参数调用委托方法,然后在委托方法内将 FirstDisplayedScrollingRowIndex 重置为该参数。事实证明,自动滚动发生在所有事件被触发之后,因此尝试在事件内部进行修改是无效的。委托方法之所以有效是因为它在事件之后被调用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接