Binding Data From Database To Grid View In ASP.NET

Introduction

Here, I will explain how to bind the data from the database to GridView in ASP.NET.

Step 1

Create table in the database (SQL Server 2012)

  1. Create the database and name it as Login.
  2. Add table (here table name: tbllogin)
  3. Set primary key to Id column.

    SQL Server

Step 2

Insert values into tbllogin table.

SQL Server

Step 3

Create new project in Visual Studio 2015.

  1. Go to File-> New-> Website -> Visual C#-> ASP.NET empty Website-> Entry Application Name-> OK.
  2. Add Web form to the Website.
    Project name-> Add-> Add New Item-> Web Form-> write name ->Add.

    SQL Server

    SQL Server

  3. HomePage.aspx (Web form) page is created.

    SQL Server

  4. Click Design Button-> Add Grid View From Toolbox. ToolBox-> Data-> Grid View.

    SQL Server

  5. Right Click on Grid View-> select View Code.

    SQL Server

  6. Add the namespaces, mentioned below, in the code back-end page.

    SQL Server

  7. After the completion of adding the namespaces, you need to write the code, as shown below.

    SQL Server

Code Explanation

  1. Write Code Inside Page Load Event.(First time Application Run)
  2. SqlConnection: is a Part of ADO.NET, used for Physical Communication between C# Applications and the database.

    Parameters in SQLConnection

    • Data Source.
      Server Name.
    • Initial Catalog.
      Database Name.

      Id and Password: Here, I am using SQL Server Authentication, so we have to provide the username and password.

      Note

      For Windows Authentication, there is no need to provide the username and password. Just write: Integrated Security=SSPI;

  3. con.Open()
    Open the connection.

  4. SqlCommand
    This is used to execute SQL statements (insert, delete, and update). Command object requires Connection Object.

  5. cmd.ExecuteReader()
    Execute SQL statements.

  6. Store Result into SqlDataReader object. rdr object contains the results.

  7. GridView1.DataSource = rdr; //GridView1 is GridView ID.
    GridView get Results from rdr object.

  8. GridView1.DataBind(); // Bind the Data

  9. con.Close(); Close Connection.

Output

SQL Server

Ebook Download
View all
Learn
View all