DataGridView Always Show VerticalScrollBar With AutoSizeColumnsMode=Fill

Viewed 2035

I have a form that has 3 DataGridView controls stacked vertically. All there grids have the same columns with the same column widths. All 3 grids have AutoSizeColumnsMode=Fill to cause the columns to fill the full width of the grid. As a result all columns line up with each other on all grids.

My issue occurs when some of the grids have more rows than will fit while others don't. This causes some of the grids to have a vertical scrollbar. When the scrollbar shows it causes the space allowed for the columns to be narrower by the width of the scrollbar. Since I am using AutoSizeColumnsMode=Fill it causes the columns to no longer line up between the grids.

Here is what I'm getting. As you can see the first grid has more that the 3 rows that will fit so there is a scrollbar. The 2nd and 3rd grids only have 3 rows and therefore don't have a scrollbar. The columns in the 2nd and 3rd grids line up but they don't line up with the first grid.

enter image description here

To resolve this I'd like to force the vertical scrollbar to ALWAYS show even if there is nothing to scroll.

I did some searching online and found a solution that almost works.

public class CustomDataGridView : DataGridView
{
    private const int BORDERWIDTH = 2;

    public CustomDataGridView()
    {
        VerticalScrollBar.Visible = true;
        VerticalScrollBar.VisibleChanged += VerticalScrollBarOnVisibleChanged;
        ClientSize = new Size(ClientSize.Width - 21, ClientSize.Height);
    }

    private void VerticalScrollBarOnVisibleChanged(object sender, EventArgs eventArgs)
    {
        if (!VerticalScrollBar.Visible)
        {
            int width = VerticalScrollBar.Width;

            VerticalScrollBar.Location =
                new Point(ClientRectangle.Width - width - BORDERWIDTH, 1);

            VerticalScrollBar.Size =
                new Size(width, ClientRectangle.Height - BORDERWIDTH);


            ClientSize = new Size(ClientSize.Width, ClientSize.Height);

            VerticalScrollBar.Show();
        }
    }
}

The problem with this is that the scrollbar shows ON TOP of the last column and covers the end of the last column header instead of forcing the the total width for all the columns to be decreased by the width of the scrollbar. I want the scrollbar to force the columns to be a little narrower like you see in the first grid.

0 Answers
Related