【问题标题】:DataGridView: Scroll down automatically only if the scroll is at the bottomDataGridView:只有当滚动在底部时才会自动向下滚动
【发布时间】:2013-04-22 05:13:51
【问题描述】:

我有一个程序使用 dataGridView 通过向 dataGridView 添加行来显示每秒自动更新的数据。

当我想在开头读一些东西时,我向上滚动,即使数据更新,滚动条也不向下,这很好。但我希望滚动条只有在 dataGridView 的底部时才会下降。

在文本中添加新行时我想要的行为:

如果滚动条位于底部,则自动向下滚动。 如果滚动条在别处,请不要滚动。

我为此编写的但很遗憾不起作用的代码是:

 private void liveDataTable_Scroll(object sender, ScrollEventArgs e)
 {
    ScrollPosition = liveDataTable.FirstDisplayedScrollingRowIndex; 

    if (ScrollPosition == liveDataTable.RowCount - 1)
    {
       IsScrolledToBottom = true;
    }
    else
    {
       IsScrolledToBottom = false;
    }            
 }
 public void AddRowToDataGridMethod()
 {
    dataTable.Rows.Add();

    if (dataWin.IsScrolledToBottom == true)
         dataWin.LiveDataTable.FirstDisplayedScrollingRowIndex = (dataWin.ScrollPosition + 1);
    else
         dataWin.LiveDataTable.FirstDisplayedScrollingRowIndex = dataWin.ScrollPosition;         
 }

【问题讨论】:

标签: c# datagridview scrollbar


【解决方案1】:

你可以试试这个:

int firstDisplayed = liveDataTable.FirstDisplayedScrollingRowIndex;
int displayed = liveDataTable.DisplayedRowCount(true);
int lastVisible = (firstDisplayed + displayed) - 1;
int lastIndex = liveDataTable.RowCount - 1;

liveDataTable.Rows.Add();  //Add your row

if(lastVisible == lastIndex)
{
     liveDataTable.FirstDisplayedScrollingRowIndex = firstDisplayed + 1;
}

所以基本上检查最后一行是否可见,以及添加新行后是否向下滚动 1 行。

【讨论】:

    【解决方案2】:

    只是想补充一下,另一种保持滚动的方法(但新行在底部)是...

    这基本上是说您显示了 10 行,并且您正在处理每一行。当它到达第 11 行时,它向上滚动 1 行,因此您的行现在显示在底部。例如,您可以添加 1,现在它将保留您的行 + 1,因此它位于底部最后一行的旁边。

    if (myRow.Displayed == false)
    {
      int intDisplayRows = myRow.Index - dataView_Database.DisplayedRowCount(false);
      dataView_Database.FirstDisplayedScrollingRowIndex = intDisplayRows;
    }
    

    【讨论】:

      【解决方案3】:
       private void dgZavod_RowsAdded_1(object sender, DataGridViewRowsAddedEventArgs e) {
           dgZavod.FirstDisplayedScrollingRowIndex = dgZavod.Rows[dgZavod.Rows.Count - 1].Index;
       }
      

      【讨论】:

        猜你喜欢
        • 2013-01-11
        • 1970-01-01
        • 1970-01-01
        • 2014-11-03
        • 2019-06-15
        • 1970-01-01
        • 1970-01-01
        • 2021-05-29
        • 2014-12-12
        相关资源
        最近更新 更多