Introduction
GridvIew control is a powerful data grid control that allows us to display the data in tabular format with sorting and pagination. It also allows us to manipulate the data as well.
Below is my ASPX code that contains a simple GridView.
GridvIew control is a powerful data grid control that allows us to display the data in tabular format with sorting and pagination. It also allows us to manipulate the data as well.
Below is my ASPX code that contains a simple GridView.
Aspx page
In the above code we have simply kept a GridView control with runat server and id attributes.
Connection String in The Web.Config are as below:
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
- <!DOCTYPE html>
- <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"></asp:GridView>
- </div>
- </form>
- </body>
- </html>
Connection String in The Web.Config are as below:
- <connectionStrings>
- <add name="MyDbConn1" connectionString="Server=LAPTOP6;Database=test;Trusted_Connection=Yes;"/>
- </connectionStrings>
Code behind
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Data.SqlClient;
- using System.Data;
- using System.Configuration;
- namespace WebApplication1 {
- public partial class WebForm1: System.Web.UI.Page {
- string constr = ConfigurationManager.ConnectionStrings["MyDbConn1"].ToString();
- protected void Page_Load(object sender, EventArgs e) {
- if (!IsPostBack) {
- GetData();
- }
- }
- private void GetData() {
- DataTable table = new DataTable();
- // get the connection
- using(SqlConnection conn = new SqlConnection(constr)) {
- // write the sql statement to execute
- string sql = "SELECT * FROM Students";
- // instantiate the command object to fire
- using(SqlCommand cmd = new SqlCommand(sql, conn)) {
- // get the adapter object and attach the command object to it
- using(SqlDataAdapter ad = new SqlDataAdapter(cmd)) {
- // fire Fill method to fetch the data and fill into DataTable
- ad.Fill(table);
- }
- }
- }
- // specify the data source for the GridView
- GridView1.DataSource = table;
- // bind the data now
- GridView1.DataBind();
- }
- }
- }

Join the conversation! Your thoughts help the community grow.