mi1an
mi1an's Blog

mi1an's Blog

Display Data Using DataReader Object in ASP.NET | ADO.NET

Display Data Using DataReader Object in ASP.NET | ADO.NET

mi1an's photo
mi1an

Published on Dec 4, 2021

1 min read

using System;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    static string cs = @"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename=C:\Users\mi1an\source\repos\DisplayData\DisplayData\App_Data\Database.mdf;Integrated Security = True";  // Connection String.
    SqlConnection con = new SqlConnection(cs);
    protected void Page_Load(object sender, EventArgs e)
    {
        string query = "SELECT * from Students";
        SqlCommand cmd = new SqlCommand(query, con);

        //1. Open Connection
        con.Open();

        //2. Read Data From Table.
        SqlDataReader reader = cmd.ExecuteReader();

        //3. Bind reader to Gridview.
        GridView1.DataSource = reader;
        GridView1.DataBind();

        //4. Close the Connection
        con.Close();

    }
 
Share this