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.
Aspx page - <%@ 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>
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:
- <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();
-
- using(SqlConnection conn = new SqlConnection(constr)) {
-
- string sql = "SELECT * FROM Students";
-
- using(SqlCommand cmd = new SqlCommand(sql, conn)) {
-
- using(SqlDataAdapter ad = new SqlDataAdapter(cmd)) {
-
- ad.Fill(table);
- }
- }
- }
-
- GridView1.DataSource = table;
-
- GridView1.DataBind();
- }
- }
- }
The final result are as below: