How can I detect when the scroll bar reaches the end of a data grid view?

…衆ロ難τιáo~ 提交于 2020-01-04 13:28:24

问题


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.


回答1:


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
  }



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/26512977/how-can-i-detect-when-the-scroll-bar-reaches-the-end-of-a-data-grid-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!