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)
- Create the database and name it as Login.
- Add table (here table name: tbllogin)
- Set primary key to Id column.
Step 2
Insert values into tbllogin table.
Step 3
Create new project in Visual Studio 2015.
- Go to File-> New-> Website -> Visual C#-> ASP.NET empty Website-> Entry Application Name-> OK.
- Add Web form to the Website.
Project name-> Add-> Add New Item-> Web Form-> write name ->Add.
- HomePage.aspx (Web form) page is created.
- Click Design Button-> Add Grid View From Toolbox. ToolBox-> Data-> Grid View.
- Right Click on Grid View-> select View Code.
- Add the namespaces, mentioned below, in the code back-end page.
- After the completion of adding the namespaces, you need to write the code, as shown below.
Code Explanation
- Write Code Inside Page Load Event.(First time Application Run)
- 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;
- con.Open()
Open the connection.
- SqlCommand
This is used to execute SQL statements (insert, delete, and update). Command object requires Connection Object.
- cmd.ExecuteReader()
Execute SQL statements.
- Store Result into SqlDataReader object. rdr object contains the results.
- GridView1.DataSource = rdr; //GridView1 is GridView ID.
GridView get Results from rdr object.
- GridView1.DataBind(); // Bind the Data
- con.Close(); Close Connection.
Output