9

I am trying to scroll down a WPF DataGrid with code behind. I use

int itemNum=0;
private void Down_Click(object sender, RoutedEventArgs e)
{
    if (itemNum + 1 > dataGridView.Items.Count - 1) return;
    itemNum += 1;
    dataGridView.UpdateLayout();
    dataGridView.ScrollIntoView(dataGridView.Items[itemNum]);
}

This scrolls down only if the itemNum row is not currently shown.

For example, If the DataGrid is long enough to hold 10 rows and I have 20 rows, I need to call this function 11 times (untill itemNum is 11) in order to scroll to the next row.

It doesnt scroll down if the row is already fits in the grid (even if its the last on the screen).

I want to achieve that when I call this method , the grid will bring the next line into the top of the grid (as the scroller does). Why isnt it working?

ASh
  • 34,632
  • 9
  • 60
  • 82
Programer
  • 1,005
  • 3
  • 22
  • 46

2 Answers2

20

Use DataGridView.FirstDisplayedScrollingRowIndex.

 int itemNum=0;
    private void Down_Click(object sender, RoutedEventArgs e)
    {
        itemNum++;
        if (itemNum > dataGridView.Items.Count - 1) return;
        //dataGridView.UpdateLayout();  <-- I don't think you need this
        dataGridView.FirstDisplayedScrollingRowIndex = itemNum;
    }

Sorry didn't realize WPF grid didn't have that. The point about scrolling stays valid tho.

ScrollIntoView will only scroll if the item is not in view, and will make it the last row if it is below the current visible lines, thus when you scroll in to view the 11th item it looks like it scrolls to the second.

This work around should work for you. You scroll to the bottom most row and then scroll up to whatever row you need. Note, here you actually need to update layout or it will ignore results of the first scroll before scrolling up again.

        dataGridView.ScrollIntoView(DataGrid1.Items[DataGrid1.Items.Count - 1]);
        dataGridView.UpdateLayout();
        dataGridView.ScrollIntoView(DataGrid1.Items[itemIndex]);
Tsabo
  • 834
  • 4
  • 9
  • 2
    Im sorry but this is a DataGrid in WPF, some rude man deleted the WPF part of my topic, probabley just to get points. What you suggested works on WINDOWS FORM DataGridView – Programer Mar 14 '12 at 08:14
  • Exactly what I needed and makes complete sense... If the currently selected item is the last, the scrolling MUST go up until that specific record is finally visible. Thanks – DRapp Jun 22 '19 at 02:40
3

Check this out, it's for a ListBox but the insight is great and it may also work for the grid:

In a few words: the items are loaded into the ListBox asynchronously, so if you call ScrollIntoView() within the CollectionChanged event (or similar) it will not have any items yet, so no scrolling.

Hope it helps, it surely helped me! ;-)

Janak Nirmal
  • 22,706
  • 18
  • 63
  • 99
Hannish
  • 1,482
  • 1
  • 21
  • 33