DataGridView: Scroll down automatically only if th

2019-06-23 15:47发布

问题:

I have a program that uses dataGridView for showing data that updates automatically every second by adding rows to dataGridView.

When I want to read something around the beginning, I scroll up, and even when data updates, the scroll bar doesn't go down, it is good. But I want the scroll bar to go down only when it is at the bottom of dataGridView.

The behavior I want when a new row is added to the text:

if the scrollbar is at the bottom, scroll down automatically. if the scrollbar is elsewhere, don't scroll.

The code I have written for this and unfortunately doesn't work is:

 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;         
 }

回答1:

You can try this:

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;
}

So basically check if the last row is visible and if it is scroll 1 row down after adding the new row.



回答2:

Just wanted to add, another method to keep it scrolling (but with the new row at the bottom) is ...

Basically what this does is say you have 10 rows displayed and your are processing each row. When it gets to the 11th row, it scrolls up by 1 row so your row in now displayed but at the bottom. You could for example add 1 and now it will stay your row + 1 so it is next to the last row from the bottom.

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;
 }