Stephen A. Fuqua (SAF) is a Bahá'í, software developer, and conservation and interfaith advocate in the DFW area of Texas.

Autoscrolling in the DataGridView

May 30, 2007

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 &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:

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

2 Comments

Works like a charm =)

Thanks for sharing.