Autoscrolling in the DataGridView
May 30, 2007
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.
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 &mdash 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:
/// Scrolls the datagrid so that the bottommost entry is always showing
private void autoScroll()
foreach (Control ctl in this.gridBatch.Controls)
if (ctl is VScrollBar)
VScrollBar scroll = (VScrollBar)ctl;
this.gridBatch.FirstDisplayedScrollingRowIndex = this.gridBatch.FirstDisplayedScrollingRowIndex + 1;