Search code examples
.netwinformsflowpanel

How do I scroll flowpanel programmatically


I am trying to flow a panel left and right with the following code.

private void btnLeft_Click(object sender, EventArgs e)
{
    if (flowPanelItemCategory.Location.X <= xpos)
    {
        xmin = flowPanelItemCategory.HorizontalScroll.Minimum;
        if (flowPanelItemCategory.Location.X >= xmin)
        {
            xpos -= 100;
            flowPanelItemCategory.Location = new Point(xpos, 0);
        }
    }
}

private void btnRight_Click(object sender, EventArgs e)
{
    if (flowPanelItemCategory.Location.X <= xpos)
    {
        xmax = flowPanelItemCategory.HorizontalScroll.Maximum;
        if (flowPanelItemCategory.Location.X < xmax)
        {
            xpos += 100;
            flowPanelItemCategory.Location = new Point(xpos, 0);
        }
    }
}

but the flow panel does not flow more that a few pixels/point (100) which corresponds to the .HorizontalScroll.Maximum;

how do i fixe this?


Solution

  • The first thing that suprises me is why you are setting the Location property. That way you are not setting a scroll position, but you're actually moving the location of the FlowLayoutPanel around.

    You could try this, but it only seems to work if you have AutoScroll set to True:

    private void btnLeft_Click(object sender, EventArgs e)
    {
        int scrollValue = flowPanelItemCategory.HorizontalScroll.Value;
        int change = flowPanelItemCategory.HorizontalScroll.SmallChange;
        int newScrollValue = Math.Max(scrollValue - change, flowPanelItemCategory.HorizontalScroll.Minimum);
        flowPanelItemCategory.HorizontalScroll.Value = newScrollValue;
        flowPanelItemCategory.PerformLayout();
    }
    
    private void btnRight_Click(object sender, EventArgs e)
    {
        int scrollValue = flowPanelItemCategory.HorizontalScroll.Value;
        int change = flowPanelItemCategory.HorizontalScroll.SmallChange;
        int newScrollValue = Math.Min(scrollValue + change, flowPanelItemCategory.HorizontalScroll.Maximum);
        flowPanelItemCategory.HorizontalScroll.Value = newScrollValue;
        flowPanelItemCategory.PerformLayout();
    }
    

    This code gets the current scroll view and increments or decrements it based on the 'scroll-step-size', but will never exceed it's boundaries.