2

I would like to detect when the scroll bar reaches the end of a data grid view, so I can run a function when this happens.

I was exploring the Scroll event, but without success.

Thanks.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user3468881
  • 35
  • 1
  • 4
  • You might be able to use knowledge of the `DataGridView`'s height and the value of the `DataGridView.ScrollingOffset` to determine that you're at the end. – MikeH Oct 22 '14 at 17:06
  • If you have the `DataGridView` in virtual mode, you would control giving it the content as it becomes visible so you would know when the last row visible. – Origin Oct 22 '14 at 17:54

3 Answers3

4

This should get you close... place this in your Scroll event and it will tell you when the last row is visible:

  int totalHeight = 0;
  foreach (DataGridViewRow row in dataGridView1.Rows)
    totalHeight += row.Height;

  if (totalHeight - dataGridView1.Height < dataGridView1.VerticalScrollingOffset)
  {
    //Last row visible
  }
MikeH
  • 4,242
  • 1
  • 17
  • 32
4

Here's another way to do it...

private void dataGrid_Scroll(object sender, ScrollEventArgs scrollEventArgs)
{
    if (dataGrid.DisplayedRowCount(false) + 
        dataGrid.FirstDisplayedScrollingRowIndex
        >= dataGrid.RowCount)
    {
        // at bottom
    }
    else
    {
        // not at bottom
    }
}
Ryan_S
  • 304
  • 3
  • 10
1

This is an alternative solution:

Scroll event runs everytime the scrollbar is being moved. Depending on your use case, this may cause issues or not so performant. So a better way is to run your check and function only when user releases the scrollbar by handling the EndScroll event.

However, you would have to use LINQ to access the datagridview's ScrollBar control and set the event handler like this:

using System.Linq;
public MyFormConstructor()
{
    InitializeComponent();
    VScrollBar scrollBar = dgv.Controls.OfType<VScrollBar>().First();
    scrollBar.EndScroll += MyEndScrollEventHandler;
}

private void MyEndScrollEventHandler(object sender, ScrollEventArgs e)
{
   if (dgv.Rows[dgv.RowCount - 1].Displayed){ // Check whether last row is visible
      //do something
   }
}
John Evans Solachuk
  • 1,953
  • 5
  • 31
  • 67