blazor-devexpress-dot-blazor-dot-dxgrid-cb3c52ad.md
Adjusts column widths to their content.
Namespace : DevExpress.Blazor
Assembly : DevExpress.Blazor.v25.2.dll
NuGet Package : DevExpress.Blazor
public void AutoFitColumnWidths()
DxGrid uses the fixed table layout algorithm to render HTML, and column widths never depend on the column content - the component does not adjust column width based on column content automatically. Refer to the following topics for additional information on how Blazor Grid renders its columns:
If you allow column resize in the UI, users can double-click a column’s right border to apply the optimal width (best fit) based on the column’s content (that is, cell content of visible columns, headers, and summaries).
In code, you can call the AutoFitColumnWidths() method to adjust column widths to their content.
Note
The AutoFitColumnWidths method has no effect if column virtualization is enabled.
The best fit algorithm uses the same units as the column’s Width property value:
Depending on the calculated values, the following outcomes are possible:
Run Demo: Fit Column Widths View Example: Fit Columns to Content and Available Space
The following example calls the AutoFitColumnWidths method to calculate initial optimal column widths. The algorithm sets Product Name , Category Name , Description , and Unit Price column widths in percentages, and in pixels for the remaining columns:
<DxGrid Data="Products"
@ref="MyGrid"
EditMode="GridEditMode.EditRow"
TextWrapEnabled="false">
<Columns>
<DxGridCommandColumn MinWidth="135" />
<DxGridDataColumn FieldName="ProductName" Width="20%" />
<DxGridDataColumn FieldName="CategoryId" Caption="Category Name">
<EditSettings>
<DxComboBoxSettings Data="Categories" ValueFieldName="CategoryId" TextFieldName="CategoryName" />
</EditSettings>
</DxGridDataColumn>
<DxGridDataColumn FieldName="Category.Description" Caption="Description" />
<DxGridDataColumn FieldName="UnitPrice" DisplayFormat="c">
<EditSettings>
<DxSpinEditSettings MinValue="0M" Mask="n3" />
</EditSettings>
</DxGridDataColumn>
<DxGridDataColumn FieldName="UnitsInStock" Width="50px" />
<DxGridDataColumn FieldName="QuantityPerUnit" Width="50px" />
<DxGridDataColumn FieldName="Discontinued" Width="50px" />
</Columns>
</DxGrid>
@code {
List<Product> Products { get; set; }
IGrid MyGrid { get; set; }
protected override void OnAfterRender(bool firstRender) {
if(firstRender) {
MyGrid.AutoFitColumnWidths();
}
}
}
See Also