Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridView: Scroll down automatically only if the scroll is at the bottom

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;         
 }
like image 727
olegoro Avatar asked Apr 28 '13 13:04

olegoro


2 Answers

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.

like image 149
MAV Avatar answered Sep 28 '22 12:09

MAV


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;
}
like image 30
Bill Avatar answered Sep 28 '22 14:09

Bill