Populate GridView from Code Behind

Introduction

GridvIew control is a powerful data grid control that allows us to display the data in tabular format with sorting and pagination. It also allows us to manipulate the data as well.

Below is my ASPX code that contains a simple GridView.

Aspx page 
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>  
  2. <!DOCTYPE html>  
  3. <html  
  4.     xmlns="http://www.w3.org/1999/xhtml">  
  5.     <head runat="server">  
  6.         <title></title>  
  7.     </head>  
  8.     <body>  
  9.         <form id="form1" runat="server">  
  10.             <div>  
  11.                 <asp:GridView ID="GridView1" runat="server"></asp:GridView>  
  12.             </div>  
  13.         </form>  
  14.     </body>  
  15. </html>   
In the above code we have simply kept a GridView control with runat server and id attributes.

Connection String in The Web.Config are as below: 
  1. <connectionStrings>  
  2.    <add name="MyDbConn1" connectionString="Server=LAPTOP6;Database=test;Trusted_Connection=Yes;"/>  
  3. </connectionStrings>    

Code behind

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Data.SqlClient;  
  8. using System.Data;  
  9. using System.Configuration;  
  10. namespace WebApplication1 {  
  11.     public partial class WebForm1: System.Web.UI.Page {  
  12.         string constr = ConfigurationManager.ConnectionStrings["MyDbConn1"].ToString();  
  13.         protected void Page_Load(object sender, EventArgs e) {  
  14.             if (!IsPostBack) {  
  15.                 GetData();  
  16.             }  
  17.         }  
  18.         private void GetData() {  
  19.             DataTable table = new DataTable();  
  20.             // get the connection    
  21.             using(SqlConnection conn = new SqlConnection(constr)) {  
  22.                 // write the sql statement to execute    
  23.                 string sql = "SELECT * FROM Students";  
  24.                 // instantiate the command object to fire    
  25.                 using(SqlCommand cmd = new SqlCommand(sql, conn)) {  
  26.                     // get the adapter object and attach the command object to it    
  27.                     using(SqlDataAdapter ad = new SqlDataAdapter(cmd)) {  
  28.                         // fire Fill method to fetch the data and fill into DataTable    
  29.                         ad.Fill(table);  
  30.                     }  
  31.                 }  
  32.             }  
  33.             // specify the data source for the GridView    
  34.             GridView1.DataSource = table;  
  35.             // bind the data now    
  36.             GridView1.DataBind();  
  37.         }  
  38.     }  
  39. }  
The final result are as below: