【问题标题】:DataGridView: how to make scrollbar in sync with current cell selection?DataGridView:如何使滚动条与当前单元格选择同步?
【发布时间】:2010-06-02 22:15:12
【问题描述】:

我有一个使用 DataGridView 作为数据表示的 Windows 应用程序。每 2 分钟,网格将用新数据刷新。为了使滚动条与添加的新数据保持同步,我必须重置它的滚动条:

dbv.Rows.Clear(); // clear rows
SCrollBars sc = dbv.ScrollBars;
dbv.ScrollBars = ScrollBars.None;
// continue to populate rows such as dbv.Rows.Add(obj);
dbv.ScrollBars = sc; // restore the scroll bar setting back

使用上面的代码,滚动条在数据刷新后重新出现。问题是应用程序需要在刷新后将某些单元格设置为选中:

dbv.CurrentCell = dbv[0, selectedRowIndex];

使用上面的代码,单元格被选中;但是,滚动条的位置并不反映所选单元格的行位置的位置。当我在刷新后尝试移动滚动条时,网格会跳转到第一行。

重置后滚动条位置似乎设置回0。设置网格的 CurrentCell 的代码不会导致滚动条重新定位到正确的位置。据我所知,DataGriadView 中没有获取或设置滚动条值的属性或方法。

我也尝试将选中的行置顶:

dbv.CurrentCell = dbv[0, selectedRowIndex];
dbv.FirstDisplayedScrollingRowIndex = selectedRowIndex;

该行将设置为顶部,但滚动条的位置仍然不同步。不确定是否有任何方法可以使滚动条的位置与代码中设置的选定行同步?

【问题讨论】:

    标签: visual-studio-2005 datagridview


    【解决方案1】:

    我找到了解决问题的答案。正如我提到的,该控件没有设置正确滚动条值的方法或属性。但是,如果直接与 UI 交互(例如触摸滚动条或网格单元),则滚动条和 DatagridView 内容将正确显示。看起来需要重新调整控件的焦点并重新绘制。

    只需使用以下代码不会导致滚动条重置:

     dgv.Select();
     // or dbv.Focuse();
    

    我发现的方法是我必须让 DatagridView 控件再次消失。幸运的是,我有一个带有多个选项卡的选项卡控件。然后我切换选项卡以重置滚动条:

    int index = myTabCtrl.SelectedIndex;
    if (index == (myTabCtrl.TabCount)) {
      dgv.SeletecedIndex = 0;
    }
    else {
      dgv.SelectedIndex = index + 1;
    }
    myTabCtrl.SelectedIndex = index;
    

    如果您无法在表单上隐藏 DatagridView,您可以简单地最小化表单,然后将其恢复。

    问题是UI上会有新鲜感。

    【讨论】:

      【解决方案2】:

      看来,TAB、SHIFT+TAB、END 键并不总是将最后一列带入可见视图。 CurrentCellChanged 事件处理程序中的以下代码似乎可以解决此问题(vb.net):

      If Me.MyDataGridView.CurrentCell IsNot Nothing Then
          Dim currentColumnIndex As Integer = e.MyDataGridView.CurrentCell.ColumnIndex
          Dim entireRect As Rectangle = _ 
                 Me.MyDataGridView.GetColumnDisplayRectangle(currentColumnIndex, False)
          Dim visiblePart As Rectangle = _
                 Me.MyDataGridView.GetColumnDisplayRectangle(currentColumnIndex, True)
      
          If (visiblePart.Width < entireRect.Width) Or (entireRect.Width = 0) Then
              Me.MyDataGridView.FirstDisplayedCell = Me.MyDataGridView.CurrentCell
              'OR Me.MyDataGridView.FirstDisplayedScrollingColumnIndex = currentColumnIndex
          End If
      End If
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-21
        • 1970-01-01
        • 2011-05-26
        • 2019-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多