Home Forums WinForms controls Xceed Grid for WinForms Column Autosize Reply To: Column Autosize

User (Old forums)
Member
Post count: 23064

I see this is an old post, but here’s my method anyway:

<code>
private void AdjustGridColumnSizes()
{
int borderWidth = Convert.ToInt32( Math.Ceiling(this.gridControl1.GridLinePen.Width) );
int remainingWidth = this.gridControl1.Width;
int remainingHeight = this.gridControl1.Height;

// subtract the row selector width
remainingWidth -= (this.gridControl1.RowSelectorPane.Visible) ? (this.gridControl1.RowSelectorPane.Width + borderWidth) : 0;

// subtract the vertical scrollbar width if it is showing
remainingHeight -= (this.groupByRow1.Visible) ? (this.groupByRow1.Height + borderWidth) : 0;
remainingHeight -= (this.cellcolumnManagerRow1column1.Visible) ? (this.columnManagerRow1.Height + borderWidth) : 0;
foreach (Xceed.Grid.DataRow myRow in this.gridControl1.DataRows)
{
if (myRow.Visible)
{
remainingHeight -= myRow.Height + borderWidth;
if (remainingHeight < 0)
{
remainingWidth -= SystemInformation.VerticalScrollBarWidth;
break;
}
}
}

// set each column to its fitted width
foreach (Xceed.Grid.Column myCol in this.gridControl1.Columns)
{
if (myCol.Visible)
{
myCol.Width = myCol.GetFittedWidth();
remainingWidth -= myCol.Width + borderWidth;
}
}

// set the last column to a width that will fill the rest of the panel
if (remainingWidth > 0)
{
this.gridControl1.Columns[this.gridControl1.Columns.Count – 1].Width += remainingWidth;
}
}
</code>

I call this method when the grid is first loaded and also when the grid’s SizeChanged event is fired. Works like a charm.

Imported from legacy forums. Posted by Lance (had 5548 views)