Binding GridView using SqlDataReader

Step 1:

Create the project as:

  1. "Start" - "All Programs" - "Microsoft Visual Studio 2013".
  2. "File" - "New Project" - "C#" - "Empty Project" (to avoid adding a master page).
  3. Give the project a name such as "BindGridfromxml" or another as you wish and specify the location.
  4. Then right-click on Solution Explorer - "Add New Item" - "WebForm1.aspx" page.
  5. Drag and Drop one grid view to the WebForm1.aspx page. Then the page will look such as follows.

WebForm1.aspx

  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>  
Step 2:

Write a Below Code In code behind file:
  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.             GetDataForReader();  
  15.         }  
  16.         private void GetDataForReader() {  
  17.             SqlConnection con = new SqlConnection(constr);  
  18.             con.Open();  
  19.             string str = "Select * from Students";  
  20.             SqlCommand cmd = new SqlCommand(str, con);  
  21.             SqlDataReader reader = cmd.ExecuteReader();  
  22.             DataTable dt = new DataTable();  
  23.             dt.Columns.Add("Id");  
  24.             dt.Columns.Add("Name");  
  25.             dt.Columns.Add("Gender");  
  26.             dt.Columns.Add("Subjects");  
  27.             while (reader.Read()) {  
  28.                 DataRow row = dt.NewRow();  
  29.                 row["Id"] = reader["Id"];  
  30.                 row["Name"] = reader["Name"];  
  31.                 row["Gender"] = reader["Gender"];  
  32.                 row["Subjects"] = reader["Subjects"];  
  33.                 dt.Rows.Add(row);  
  34.             }  
  35.             GridView1.DataSource = dt;  
  36.             GridView1.DataBind();  
  37.             reader.Close();  
  38.             con.Close();  
  39.         }  
  40.     }  
  41. }