Resize DataGridView width to fit Columns

c#, datagridview, winforms

Solution

Execute the following code after the grid is loaded with data and the columns have been sized accordingly (assuming you're setting the columns' AutoSize property at runtime).

dataGridView1.Width =
    dataGridView1.Columns.Cast<DataGridViewColumn>().Sum(x => x.Width)
    + (dataGridView1.RowHeadersVisible ? dataGridView1.RowHeadersWidth : 0) + 3;

What it's doing:

- Totals up the widths of all columns (using LINQ),

- Sees if the "row header" is visible and adds that width too, if it is,

- Adds `3` more because without that the horizontal scrollbar kept showing up - possibly because of margin/padding around the grid, I'm not sure.

Problem

I have a `DataGridView` that is filled programmatically. The columns are set to auto-resize according to cell content. The `DataGridView` will be populated with parts information regarding hydraulic and pneumatic schematics. My form only has a `SplitContainer`, a `PictureBox` and the `DataGridView`. The `SplitterDistance` is linked to the width of the `DataGridView`. The `DataGridView` will only have a maximum of 6 columns ("Index", "Part Number", "Serial Number", "Drawing Number", "Page Number", "Revision Number") and a minimum of 2 columns depending on the schematics requirements. So I want to resize the control accordingly. How can I get the `DataGridView` control to resize to the total width of the columns so that the scrollbar doesn't show?

Original source

Related problems