Reputation: 35
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.
Upvotes: 2
Views: 5168
Reputation: 2105
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
}
}
Upvotes: 1
Reputation: 310
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
}
}
Upvotes: 4
Reputation: 4395
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
}
Upvotes: 4