【问题标题】:DataGridView Preserve Selected Index and Scroll Position after update and reloadDataGridView 在更新和重新加载后保留选定的索引和滚动位置
【发布时间】:2016-01-13 20:59:01
【问题描述】:

我有一些问题,现在不知道如何在DataGridView 中保留滚动位置。

我有超过 1000 行,滚动回编辑的行很痛苦。刷新数据后如何保留滚动位置并滚动到已编辑的行?

【问题讨论】:

    标签: c# winforms datagridview datagridviewrow


    【解决方案1】:

    保存行索引,进行刷新,然后设置FirstDisplayedScrollingRowIndex 属性。

    int index = dataGridView1.CurrentRow.Index;
    
    /*
     * Your Refresh Code
     */
    
    dataGridView1.FirstDisplayedScrollingRowIndex = index;
    

    【讨论】:

    • 此代码有效,但在滚动到最后一个滚动位置之前,滚动条会在几分之一秒内跳到顶部。不知道怎么处理。
    • @NiravParsana 我目前无法对此进行测试,但也许可以尝试将此代码包装在 dataGridView1.SuspendLayout().ResumeLayout() 中。如果不是这样,也许其他 to suspend the grid 会起作用?
    【解决方案2】:

    可以在重新加载数据前获取当前行索引:

    int currentIndex= dataGridView1.CurrentRow.Index;
    

    然后在重新加载数据后,您可以使用以下任一选项:

    滚动并设置当前行:

    this.dataGridView1.CurrentCell =  this.DataGridView1.Rows[currentIndex].Cells[0];
    

    滚动:

    dataGridView1.FirstDisplayedScrollingRowIndex = currentIndex;
    

    【讨论】:

      【解决方案3】:
      void SomeMethod()
      {
          if (dataGridView != null &&
              dataGridView.CurrentRow != null)
                  this.Invoke(new Action(GetScrollingIndex));
          UpdateTable();
          if (dataGridView != null &&
              dataGridView.CurrentRow != null)
                  this.Invoke(new Action(SetScrollingIndex));
      }
      void GetScrollingIndex()
      {
          scrollingIndex = dataGridView.FirstDisplayedCell.RowIndex;
      }
          
      void SetScrollingIndex()
      {
          dataGridView.FirstDisplayedScrollingRowIndex = scrollingIndex;
      }
      

      【讨论】:

      • 这仍然有点不稳定,因为用户在更新时失去了滚动条的焦点,但它可以工作
      猜你喜欢
      • 2014-12-05
      • 2020-03-14
      • 1970-01-01
      • 2011-01-27
      • 2014-11-18
      • 1970-01-01
      • 1970-01-01
      • 2016-03-07
      • 2012-10-16
      相关资源
      最近更新 更多