How to disable horizontal scrollbar for table panel in winforms

Viewed 23952

Hi I've a tablelayoutpanel and I'm binding controls to it dynamically. When the item count exceeds the height of panel obviously vertical scroll bar appearing there is no problem.

But the same time horizontal scroll bar is also appearing even the items width is less than the width of panel. How can i prevent this?

10 Answers

Is the issue that your items are exactly the width of the the layout panel, so that when the verticle scroll appears it cuts into your controls a bit, forcing the horizontal scroll? If so, you can either make your controls smaller width-wise to account for the possibility of the scrollbar, or you can try to adjust them when the scroll bar appears.

I found a perfect solution about this problem by using reflect. You can try following codes:

static MethodInfo funcSetVisibleScrollbars;
static EventHandler ehResized;

public static void DisableHorizontalScrollBar(this ScrollableControl ctrl)
{
     //cache the method info
     if(funcSetVisibleScrollbars == null)
     {
           funcSetVisibleScrollbars = typeof(ScrollableControl).GetMethod("SetVisibleScrollbars",
                BindingFlags.Instance | BindingFlags.NonPublic);
     }

     //init the resize event handler
     if(ehResized == null)
     {
           ehResized = (s, e) =>
           {
                funcSetVisibleScrollbars.Invoke(s, new object[] { false, (s as ScrollableControl).VerticalScroll.Visible });
           };
     }

     ctrl.Resize -= ehResized;
     ctrl.Resize += ehResized;
}

I know it has been long this question is here. But probably someone else may benefit from the solution worked for me.

The trick is that disabling the horizontal scroll bar does nothing if auto scroll property is true. So just disable auto scroll, disable horizontal scrollbar and then switch the auto scroll to true again. This works for me.

Just add the following code to some place such as the constructor or Form Load event.

tableLayoutPanel1.AutoScroll = false;
tableLayoutPanel1.HorizontalScroll.Enabled = false;
tableLayoutPanel1.AutoScroll = true;

None of these solution worked in every case; I ended up needing a combination of them:

public void hideHorizontalScrollBar(ref TableLayoutPanel pan)
{
    if (!pan.HorizontalScroll.Visible)
        return;
    pan.Padding = new Padding(0, 0, 0, 0);
    while (!!pan.HorizontalScroll.Visible || pan.Padding.Right >= SystemInformation.VerticalScrollBarWidth * 2)
    pan.Padding = new Padding(0, 0, pan.Padding.Right + 1, 0);
}

Important: this can be called once on form load, but must also be called in the layout resize event.

Related