Monday, May 8, 2017

How to fill the GridView using SqlDataReader in asp.net C#

Introduction:-


Hello all today i will explain you "How to fill gridview from SqlDataReader in asp.net c#"

Please follow the below steps:-

1)Create a connection string in Web.config File.

 <connectionStrings>
    <add name="sqlConnecrtion" connectionString="Data Source=MICROSOFTDOTNET;Initial Catalog=SEPTNew;Trusted_connection=True" />   
  </connectionStrings>

2) Drag the GridView on to the .aspx page.

3) write the below code in your .aspx.cs 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;
using System.Data.SqlClient;
using System.Configuration;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        string _con = ConfigurationManager.ConnectionStrings["sqlConnecrtion"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {
           if (!IsPostBack)
            {
               
               gatdataUsingReader();
            }

            }
        private void gatdataUsingReader()
        {
            using (SqlConnection con2 = new SqlConnection(_con))
            {
                con2.Open();
                using(SqlCommand cmd1=new SqlCommand("Select * from sales",con2))
                {
                    SqlDataReader dr = cmd1.ExecuteReader();
                    GridView2.DataSource = dr;
                    GridView2.DataBind();
                } 
            }
        }
        
        }
        
    } 
}


Execute your program using F5 or start project.



--------------------------Thank you ------------------------- 


No comments:

Post a Comment