views:

777

answers:

2

I've got a chunk of C# code that is supposed to set VerticalScroll.Value within a class that inherits from UserControl. It gets called when any child object of the class changes sizes. The class has its AutoScroll property set to true.

    public void ScrollTo(int top)
    {
        if (top >= this.VerticalScroll.Minimum && top <= this.VerticalScroll.Maximum)
        {
            this.VerticalScroll.Value = top;
        }
    }

The problem is, when tracing through the code, sometimes this.VerticalScroll.Value gets set, sometimes it keeps the value that it had before this method was called.

Is this a bug in VS, or are there known conditions under which the value will ignore attempts to set it?

Thanks, Rob

+2  A: 

I was running into the same problem, and I found a solution on the MSDN webpage (won't let me post links, 'cause I'm a new user).

The suggested solution was to assign to .Value twice, and it worked for me:

int newVerticalScrollValue = pDashboard.VerticalScroll.Value - pDashboard.VerticalScroll.SmallChange;

pDashboard.VerticalScroll.Value = newVerticalScrollValue;

pDashboard.VerticalScroll.Value = newVerticalScrollValue;

@Aowyn, thanks a tonne, I just had a chance to test this and it works great.
Robert Gowland
+5  A: 

I was having the same problem and came upon the solution in some dev forum. After setting the VerticalScroll.Value, you have to call PerformLayout() to make the scrolling control update. So do this:

scrollingcontrol.VerticalScroll.Value = top;
scrollingcontrol.PerformLayout();

This makes more sense than setting .Value twice, though it seems to have the same effect.

skypecakes
Aw c'mon, no love for my answer, even though it is "better" than the accepted answer?
skypecakes
I'd have to test it to up-vote it. Since the project was completed in May, you'll have to wait until I get a free moment.
Robert Gowland
skypecakes' answer is correct. I had the exact same problem today and calling PerformLayout() solved it. Thanks.
Kyle Gagnet