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

cdatagridviewscrollbar

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

Best Answer

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.

Related Topic