ASP.NET Simple GridView

The GridView control offers a multitude of integrated functionalities, empowering users to effortlessly sort, update, delete, select, and page through items within the control. To establish a connection between the GridView control and a data source control, you can utilize the binding capabilities.

By setting the DataSourceID property of the GridView control to the ID value of the desired data source control, you can seamlessly bind the data source to the GridView control, thereby enabling efficient data manipulation. This streamlined approach facilitates the synchronization of data between the GridView and the data source, ensuring a smooth and coherent user experience.

asp.net gridview

Download Database

In this article I have used Microsoft's Pubs database for sample data. You can download it free from the following link.

Download

To begin generating a GridView in your ASP file, it is essential to create a ConnectionString within your web.config file. To accomplish this, follow these steps:

  1. Locate the web.config file in your project's directory within Visual Studio.
  2. Double-click on the web.config file to open it.
  3. Within the web.config file, identify the appropriate section to add the ConnectionString code.
web.config file

Web.Config File

<?xml version="1.0"?> <configuration> <connectionStrings> <add name="SQLDbConnection" connectionString="Server=Your-Server-Name; Database=pubs; User Id=sa; password= your-passoword" providerName="System.Data.SqlClient" /> </connectionStrings> </configuration>

After create the connectionstring in the web.config file, you should call the connectionstring in your asp page and issue the select command.

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:SQLDbConnection %>" SelectCommand="select au_lname,phone,address,city from [authors]" />

When you run this asp.net application , your output look likes the following image.

simple-gridview

The following is the full asp source code for selecting au_lname,phone,address,city from the authors table in the Pubs database.

Asp.net gridview example

Default.aspx

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <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" DataSourceID="SqlDataSource1" /> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:SQLDbConnection %>" SelectCommand="select au_lname,phone,address,city from [authors]" /> </div> </form> </body> </html>