aresz
aresz

Reputation: 2649

Programmatically scrolling datagridview by increments until it hits bottom, then scroll back to top

I'm trying to scroll my Datagridview programmatically by increments of 2. When it reaches the bottom, I'd like to reset the scroll back to the top.

Here is my current code:

private int scrollPosition = 0;

            if(scrollPosition == 0)
            {
                // This means the scroll is at the top
                scrollPosition+=2;

            }
            else if(scrollPosition > 0 && scrollPosition < dataGridView1.RowCount-1 -2)
            {
                // This means the scroll is somewhere in the middle
                scrollPosition+=2;
            }
            else
            {
                // This means the scroll is at the bottom
                scrollPosition = 0;

            }
            dataGridView1.FirstDisplayedScrollingRowIndex = scrollPosition;

That code is inside a method that gets called every 10 seconds.

I have tried debugging the code. Based on what I saw, the code never triggers the else statement. Hence, it does not reset the scroll back to the top. What logic did I do wrong?

Update: My mistake, it triggers the else statement at some point. But it doesn't trigger the else statement the moment the scroll is at the bottom already. Since I have 20 entries in my Datagridview, it takes a while for the scroll position to get near that value.

The Datagridview scroll is already at the bottom before my scrollPosition reaches a value that would trigger the else statement.

Is there a more accurate variable I can compare my scrollPosition to? So that when my Datagridview scroll is at the bottom already, it triggers the else statement as it should at the right time.

Upvotes: 1

Views: 4015

Answers (1)

TaW
TaW

Reputation: 54453

Your calculation doesn't take the number of displayed Rows into account.

Here is how you can calculate them, provided the Rows all have the same Height:

rVisible = dataGridView1.Height / dataGridView1.Rows[0].Height - 1;

Or as Mark suggested:

rVisible = dataGridView1.DisplayedRowCount(false);

Now you can simplify your scrolling code to this:

if (dataGridView1.FirstDisplayedScrollingRowIndex + rVisible < dataGridView1.Rows.Count)
    dataGridView1.FirstDisplayedScrollingRowIndex += 2; 
else dataGridView1.FirstDisplayedScrollingRowIndex = 0;

No need for the scrollPosition variable.

In your original solution you could also check to see if FirstDisplayedScrollingRowIndex stops growing, which it does once the last row is visible, but this is simpler. If the rows have varying heights either DisplayedRowCount or that latter way should be used so you won't have to sum up the varying heights..

Upvotes: 4

Related Questions