Kfir
Kfir

Reputation: 105

datagridview not autoresizing properly

I'm trying to autosize my dgv's width and height, However, it leaves me with big spaces in width, something isn't right.

This is the code I'm using:

int height = 0;
foreach (DataGridViewRow row in dgv.Rows)
{
    height += row.Height;
}
height += dgv.ColumnHeadersHeight;

int width = 0;
foreach (DataGridViewColumn col in dgv.Columns)
{
    width += col.Width;
}
width += dgv.RowHeadersWidth;

dgv.ClientSize = new Size(width + 2, height + 2);

dgv with spaces in width - example 1

dgv with spaces in width - example 2

Upvotes: 2

Views: 540

Answers (2)

Cataklysim
Cataklysim

Reputation: 677

Usually a DataGridView defines that properties by itself. They got the properties ColumnHeadersHeightSizeMode which you can set to AutoSize.

With AutoSizeColumnsMode you can even tell the DataGridView which Object needs to resize. (Like ColumnHeader, AllCellsExceptHeader, AllCells.

You can find those easily in the Property Window. No need to Code that.

Upvotes: 0

Robert S.
Robert S.

Reputation: 2042

Have a look at DataGridView.AutoSizeColumnsMode. You can also force a resize with DataGridView.AutoResizeColumns(); then.

You just added all column widths together but who says that the column widths are as desired?

Upvotes: 2

Related Questions