ASP.NET DataGrid Control: Displaying Data in a Web Grid (Deprecated)

This guide provides a comprehensive overview of the now-deprecated ASP.NET DataGrid control, explaining how to use it to display data from various sources (DataTable, database) in a scrollable grid on a web page. Includes code examples and illustrative output.



ASP.NET DataGrid Control

Introduction to the DataGrid Control

The ASP.NET DataGrid control (now deprecated) is a server-side control used to display data in a scrollable grid format on a web page. It requires a data source (DataTable or database) to populate the grid. You can add a DataGrid control to your web form using the Visual Studio drag-and-drop interface.

DataGrid Example using a DataTable

This example demonstrates how to bind data from a DataTable to a DataGrid control.

ASPX Code (DataGridExample2.aspx)

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DataGridExample2.aspx.cs" Inherits="DataGridExample.DataGridExample2" %>
<asp:DataGrid ID="DataGrid1" runat="server"></asp:DataGrid>
C# CodeBehind (DataGridExample2.aspx.cs)

using System;
using System.Data;
namespace DataGridExample
{
public partial class DataGridExample2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("ID");
table.Columns.Add("Name");
table.Columns.Add("Email");
table.Rows.Add("101", "Deepak Kumar", "deepak@example.com");
table.Rows.Add("102", "John", "john@example.com");
table.Rows.Add("103", "Subramanium Swami", "subramanium@example.com");
table.Rows.Add("104", "Abdul Khan", "abdul@example.com");
DataGrid1.DataSource = table;
DataGrid1.DataBind();
}
}
}
Output

(A screenshot of the DataGrid output showing the DataTable data would be included here.)

DataGrid Example using a Database

This example shows how to bind data from a SQL Server database to a DataGrid.

ASPX Code (DataGridExample.aspx)

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DataGridExample.aspx.cs" Inherits="AdoNetExample.DataGridExample" %>
<asp:DataGrid ID="DataGrid1" runat="server"></asp:DataGrid>
C# CodeBehind (DataGridExample.aspx.cs)

using System;
using System.Data;
using System.Data.SqlClient;
namespace AdoNetExample
{
public partial class DataGridExample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("data source=.; database=student; integrated security=SSPI"))
{
SqlDataAdapter sde = new SqlDataAdapter("Select * from student", con);
DataSet ds = new DataSet();
sde.Fill(ds);
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
}
}
}
}
Sample Data (student table)
ID Name Email
101 Deepak Kumar deepak@example.com
102 John john@example.com
103 Subramanium Swami subramanium@example.com
104 Abdul Khan abdul@example.com
Output

(A screenshot of the DataGrid output showing data from the database would be included here.)