Step 1:
Create the project as:
- "Start" - "All Programs" - "Microsoft Visual Studio 2013".
- "File" - "New Project" - "C#" - "Empty Project" (to avoid adding a master page).
- Give the project a name such as "BindGridfromxml" or another as you wish and specify the location.
- Then right-click on Solution Explorer - "Add New Item" - "WebForm1.aspx" page.
- Drag and Drop one grid view to the WebForm1.aspx page. Then the page will look such as follows.
WebForm1.aspx
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
- <!DOCTYPE html>
- <html
- xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:GridView ID="GridView1" runat="server"></asp:GridView>
- </div>
- </form>
- </body>
- </html>
Step 2:
Write a Below Code In code behind file:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Data.SqlClient;
- using System.Data;
- using System.Configuration;
- namespace WebApplication1 {
- public partial class WebForm1: System.Web.UI.Page {
- string constr = ConfigurationManager.ConnectionStrings["MyDbConn1"].ToString();
- protected void Page_Load(object sender, EventArgs e) {
- GetDataForReader();
- }
- private void GetDataForReader() {
- SqlConnection con = new SqlConnection(constr);
- con.Open();
- string str = "Select * from Students";
- SqlCommand cmd = new SqlCommand(str, con);
- SqlDataReader reader = cmd.ExecuteReader();
- DataTable dt = new DataTable();
- dt.Columns.Add("Id");
- dt.Columns.Add("Name");
- dt.Columns.Add("Gender");
- dt.Columns.Add("Subjects");
- while (reader.Read()) {
- DataRow row = dt.NewRow();
- row["Id"] = reader["Id"];
- row["Name"] = reader["Name"];
- row["Gender"] = reader["Gender"];
- row["Subjects"] = reader["Subjects"];
- dt.Rows.Add(row);
- }
- GridView1.DataSource = dt;
- GridView1.DataBind();
- reader.Close();
- con.Close();
- }
- }
- }