Stephen A. Fuqua (saf)

a Bahá'í, software engineer, and nature lover in Austin, Texas, USA

Autoscrolling in the DataGridView

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

Comments

imported from old Movable Type blog

author: obisunk
date: ‘2007-09-29 03:42:29 -0500’

Works like a charm =)

Thanks for sharing.


author: Praveen
date: ‘2008-03-19 18:07:31 -0500’
url: http://praveensg.com

Beautiful.

Posted with : Tech, Microsoft .NET Framework