In this article I will explain with an example, how to populate (bind) WebGrid using ADO.Net in ASP.Net Core MVC.
Inside the Controller, the records from the Database Table will be fetched using traditional ADO.Net method i.e. using SqlConnection, SqlCommand, SqlDataAdapter, etc.
The fetched records will be populated into a DataSet which will be used to populate the WebGrid in ASP.Net Core MVC.
MVC6 Grid for ASP.Net Core
This article makes use of MVC6 Grid library for implementing WebGrid, as it is not available by default in .Net Core.
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
You will need to import the following namespaces.
The Controller consists of the following Action method.
Action method for handling GET operation
Inside this Action method, the Top 10 records are fetched from the Customers Table using ADO.Net.
The records are inserted into a DataSet using SqlDataAdapter class object.
Finally, the DataSet is returned to the View.
public class HomeController : Controller
public IActionResult Index()
string constr = @"Data Source=.\SQL2019;Initial Catalog=Northwind;Integrated Security=true";
using (SqlConnection con = new SqlConnection(constr))
string query = "SELECT TOP 10 CustomerID, ContactName, City, Country FROM Customers";
using (SqlCommand cmd = new SqlCommand(query, con))
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
using (DataSet ds = new DataSet())
Inside the View, in the very first line DataSet is declared as Model for the View.
The System.Data, NonFactors.Mvc.Grid namespaces and mvc-grid.css file are inherited inside the View.
The DataTable is passed to the Grid function of the MVC6 Grid HTML Helper class.
The columns have been added using the Build method of the MVC6 Grid HTML Helper class.
Inside the Build method of the MVC6 Grid HTML Helper class, a foreach loop will be executed over the Columns.
Inside the loop, dynamically columns have been added using the Add method and the Header Text of the column is set using the Titled function by passing the Column Name.
Layout = null;
<meta name="viewport" content="width=device-width" />
<link href="~/css/mvc-grid/mvc-grid.css" rel="stylesheet" />
foreach (DataColumn column in Model.Tables.Columns)
columns.Add(model => model[column.ColumnName]).Titled(column.ColumnName);