New to Telerik UI for ASP.NET MVCStart a free 30-day trial

Automatically Fit Width of Grid Columns to Show All Data

Environment

ProductProgress® ASP.NET MVC GridVersion2023.3.1114

Description

How can I have the columns of a ASP.NET MVC Grid automatically fit their width to accommodate their content?

Solution

  1. Subscribe to the DataBound event of the Grid.
  2. Loop through the Grid columns and pass the column index to the client-side autoFitColumn method.
Razor
  @(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.ProductViewModel>()
      .Name("Grid")
      .Columns(columns =>
      {
              columns.Bound(p => p.ProductName).Title("Product Name").Width(320);
              columns.Bound(p => p.UnitPrice).Title("Unit Price").Width(150);
              columns.Bound(p => p.UnitsInStock).Title("Units In Stock").Width(150).MinScreenWidth(800);
              columns.Bound(p => p.UnitsOnOrder).Title("Units On Order").Width(150).MinScreenWidth(800);
              columns.Bound(p => p.Discontinued).Width(130);
              columns.Command(command => command.Destroy()).Width(160);
      })
      .Pageable()
      .Events(events => events.DataBound("onDataBound"))
      .DataSource(dataSource => dataSource
          .Ajax()
          .PageSize(20)
          .Model(model =>
          {
              model.Id(p => p.ProductID);
              model.Field(p => p.ProductID).Editable(false);
          })
          .Create("Products_Create", "Grid")
          .Read("Products_Read", "Grid")
          .Update("Products_Update", "Grid")
          .Destroy("Products_Destroy", "Grid")
      )
  )

Notes

Applying auto-sizing to all columns of the Grid is a resource intensive operation. Depending on the number of configured columns, it may cause performance issues on the client-side.

More ASP.NET MVC Grid Resources

See Also