Bind Grid to DataTable
Environment
| Product | Telerik UI for ASP.NET MVC Grid |
| Product version | 2025.1.227 |
Description
How can I bind the Grid to a DataTable?
Solution
To bind the Grid to a DataTable, you need to configure the Grid's DataSource to read from the DataTable and set up the necessary columns and properties.
This approach is applicable when binding to any
dynamicmodel.
The example relies on the following key steps:
-
Define the View's model as
System.Data.DataTableand set up the Grid columns based on theDataTablecolumns. Also, using the same approach as for the columns, define the fields in theModelconfiguration of the DataSource.Razor@using Kendo.Mvc.UI @model System.Data.DataTable @(Html.Kendo().Grid<dynamic>() .Name("Grid") .Columns(columns => { foreach (System.Data.DataColumn column in Model.Columns) { var c = columns.Bound(column.ColumnName); } columns.Command(cmd=>cmd.Edit()); }) .Pageable() .Sortable() .Editable(ed=>ed.Mode(GridEditMode.PopUp)) .Filterable() .Groupable() .Scrollable() .DataSource(dataSource => dataSource .Ajax() .Model(model => { var id = Model.PrimaryKey[0].ColumnName; model.Id(id); foreach (System.Data.DataColumn column in Model.Columns) { var field = model.Field(column.ColumnName, column.DataType); if (column.ColumnName == id) { field.Editable(false); } } }) .Read(read => read.Action("Read", "Home")) .Update(update => update.Action("Update", "Home")) ) ) -
Populate the
DataTablewith the respective data and pass it to the View.C#public ActionResult Index() { DataTable products = Products(); return View(products); } private DataTable Products() { var connection = ConfigurationManager.ConnectionStrings["GridBindingDataTableEntities"].ConnectionString; using (var dataAdapter = new SqlDataAdapter("SELECT * from Products", connection)) { var dataTable = new DataTable(); dataAdapter.Fill(dataTable); dataAdapter.FillSchema(dataTable, SchemaType.Mapped); return dataTable; } }
Sample Project
To review the complete project, refer to ASP.NET MVC application in the UI for ASP.NET MVC Examples repository.
The sample project resolves two main issues related to:
Editing
The Grid does not have an instance to a model object and cannot infer field types. You need to provide the model field definitions yourself.
Solution
The metadata of the DataTable contains this information. Pull it into the model definition as illustrated in Index.cshtml.
Aggregates
The aggregates suffer from a lack of type-information as well. The ToDataSourceResult method does not have information about the field types and fails to compute the aggregates.
Solution
Provide type-information for the requested aggregates in the DataSourceRequest object. For more information, refer to HomeController.cs.
More ASP.NET MVC Grid Resources
- ASP.NET MVC Grid Documentation
- ASP.NET MVC Grid Demos
- ASP.NET MVC Grid Product Page
- Telerik UI for ASP.NET MVC Video Onboarding Course (Free for trial users and license holders)
- Telerik UI for ASP.NET MVC Forums