Skip to main content

Autoscrolling in the DataGridView

· 2 min read

Problem

In a .Net 2.0 Windows Forms application, user action causes a new

row to be added to a DataGridView control. When the viewport fills up, causing the vertical scrollbar to appear, the most recent entry is hidden "below the fold" — off the screen. Users want to see the latest entry at all times.

Solution

turns out to be relatively easy. But first, it is important to know what control you're dealing with. Because I don't program in Windows Forms very often, I forgot that I'm now using a DataGridView control instead of a DataGrid control. So that stymied me for a bit.

First thing I needed was to recognize that the latest entry is now off the screen — in other words, I had to recognize that the scrollbar is showing. Found a very helpful newsgroup posting for that.

That posting actually describes moving the scrollbar independently of the grid. Not exactly what I want. After a bit more searching, I found that the FirstDisplayedScrollingRowIndex property. That does it. I have my solution:

/// <summary>
/// Scrolls the datagrid so that the bottommost entry is always showing
/// </summary>
private void autoScroll()
{
if (this.gridBatch.Visible)
{
foreach (Control ctl in this.gridBatch.Controls)
{
if (ctl is VScrollBar)
{
VScrollBar scroll = (VScrollBar)ctl;
if (scroll.Visible)
this.gridBatch.FirstDisplayedScrollingRowIndex = this.gridBatch.FirstDisplayedScrollingRowIndex + 1;
}
}
}
}