Dynamic DataGrid Width Based on Column Widths

Hi,

I have a question regarding the RadzenDataGrid column resizing behavior.

Is it possible to achieve the following behavior?

  • Users can resize the columns, so the total width of the grid can change dynamically.

  • The grid has a maximum width.

  • If the total width of all columns exceeds the maximum grid width, a horizontal scrollbar is displayed.

  • If the total width of all columns does not exceed the maximum grid width, the grid automatically shrinks to fit the total width of its columns.

Thanks in advance!

Hi,

There is no built-in option for this: the grid table is rendered with width: 100% and table-layout: fixed, so the grid always fills its container. However, you can achieve it with a ColumnResized handler that sets the grid width to the sum of the column widths, capped by max-width. Every column needs a Width (or use the grid ColumnWidth), and box-sizing: content-box is needed because the grid has a 1px border on each side.

<RadzenDataGrid Data="@employees" TItem="Employee" AllowColumnResize="true"
                ColumnResized=@OnColumnResized Style="@GridStyle">
    <Columns>
        <RadzenDataGridColumn Property="EmployeeID" Title="ID" Width="60px" MinWidth="40px" />
        <RadzenDataGridColumn Property="FirstName" Title="First Name" Width="150px" MinWidth="40px" />
        <RadzenDataGridColumn Property="LastName" Title="Last Name" Width="150px" MinWidth="40px" />
        <RadzenDataGridColumn Property="Title" Title="Title" Width="200px" MinWidth="40px" />
        <RadzenDataGridColumn Property="City" Title="City" Width="120px" MinWidth="40px" />
    </Columns>
</RadzenDataGrid>

@code {
    double totalWidth = 60 + 150 + 150 + 200 + 120;

    string GridStyle => $"box-sizing: content-box; width: {totalWidth.ToString(CultureInfo.InvariantCulture)}px; max-width: 600px;";

    void OnColumnResized(DataGridColumnResizedEventArgs<Employee> args)
    {
        totalWidth = args.Widths.Values.Sum();
    }
}

When the total is below max-width the grid shrinks to fit the columns; when it exceeds it, the grid stays at max-width and shows a horizontal scrollbar.