SAF(NET) = STEPHEN A. FUQUA operating on the Web since 1995

Stephen is a web developer, Bahá'í, and interfaith activist in St. Paul, Minnesota. He likes to write about religion, social justice, sustainability, science, programming, &c.

May 30, 2007

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

Comments

obisunk — September 29, 2007

Works like a charm =)

Thanks for sharing.

Praveen — March 19, 2008

Beautiful.

Post a comment

Remember personal info?




deprecated

On safnet.com

Other sites managed or developed by S.A.F.

S.A.F. elsewhere on the web

  • LinkedIn
    LinkedIn can actually be useful when looking for prospective hires and business or organizational partners
  • GoodReads
    A fun and relatively-unknown social networking site geared towards one's book list
  • Live Journal
    Mirror of the blog at safnet.com, so that a few LJ friends can more easily read and comment there