Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGrid ScrollIntoView - how to scroll to the first row that is not shown?

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?

like image 231
Programer Avatar asked Mar 12 '12 13:03

Programer


2 Answers

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! ;-)

like image 162
Hannish Avatar answered Nov 02 '22 02:11

Hannish


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]);
like image 33
Tsabo Avatar answered Nov 02 '22 04:11

Tsabo