New to Telerik UI for ASP.NET Core? Start a free 30-day trial
Automatically Fit Width of Grid Columns to Show All Data
Environment
Product | Progress® ASP.NET Core Grid | Version | 2023.3.1114 |
Description
How can I have the columns of a ASP.NET Core Grid automatically fit their width to accommodate their content?
Solution
- Subscribe to the
DataBound
event of the Grid. - 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")
)
)
Explore the solution in REPL
You can continue experimenting with the code sample above by running it in the Telerik REPL server playground:
- Sample code with the Autofit Grid Columns HtmlHelper
- Sample code with the Autofit Grid Columns TagHelper
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.