---
title: "GridView Control in ASP.Net"  
description: "The GridView control enables you to connect to a data source and display data in tabular format.    aspGridViewThe GridView control supports the follo"  
author: "Pushpendra Singh"  
published: 2010-10-30  
updated: 2020-03-04  
canonical: https://www.mindstick.com/articles/184/gridview-control-in-asp-dot-net  
category: "ado.net"  
tags: ["ado.net"]  
reading_time: 5 minutes  

---

# GridView Control in ASP.Net

The GridView control enables you to connect to a [data source](https://www.mindstick.com/forum/160659/how-do-you-create-a-custom-filter-to-filter-any-text-in-the-data-source-in-angularjs) and [display data](https://www.mindstick.com/forum/34030/how-to-display-data-in-the-table-using-angular-js) in [tabular format](https://www.mindstick.com/forum/34668/how-to-embed-tabular-format-data-in-outlook-using-asp-dot-net-mvc).\

```
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
```

![GridView Control in ASP.Net](https://www.mindstick.com/mindstickarticle/72e6f660-f985-4470-99d6-81f472882868/images/1c6fe5e0-9d5e-40a0-bcc3-2bbb59eac928.png)

**The GridView control supports the following features:**

· Binding to data source controls.

· Built -in sorting capabilities.

· Built-in updating and deleting capabilities.

· Build-in paging capabilities.

· Built-in row selection capabilities.

· New column types such as CheckBoxField and Image Field.

· Multiple data fields for the hyperlink columns.

· Multiple data key fields for selection, updates, and deletes.

· Customizable appearance through themes and styles.

**Code:**

```
<asp:GridView   ID="GridView1"runat="server"  AllowPaging="True" AutoGenerateColumns="False"OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowUpdating="GridView1_RowUpdating" OnRowCommand="GridView1_RowCommand" OnRowDeleting="GridView1_RowDeleting"ShowFooter="True" CellPadding="4" ForeColor="#333333" GridLines="None">  <RowStyle BackColor="#F7F6F3" ForeColor="#333333" /><Columns> <asp:TemplateField  HeaderText="ID"> <ItemTemplate> <asp:Label ID="lblid" runat="server" Text='<%# Eval("id")%>'>   </asp:Label> </ItemTemplate> <EditItemTemplate> <asp:Label ID="lblid1" runat="server" Text='<%# Eval("id")%>'> </asp:Label> </EditItemTemplate> <FooterTemplate> <asp:TextBox ID="txtid2" runat="server"></asp:TextBox></FooterTemplate> </asp:TemplateField>            <asp:TemplateField HeaderText="PASS"><ItemTemplate><asp:Label ID="lblid2" runat="server" Text='<%# Eval("pass")%>'> </asp:Label></ItemTemplate><EditItemTemplate><asp:TextBox ID="txtid3"runat="server"Text='<%#Eval("pass")%>'></asp:TextBox> </EditItemTemplate><FooterTemplate><asp:TextBox ID="txtid4" runat="server"></asp:TextBox></FooterTemplate></asp:TemplateField>  <asp:TemplateField HeaderText="ID"><ItemTemplate><asp:Label ID="lblid3" runat="server" Text='<%# Eval("name")%>'> </asp:Label></ItemTemplate><EditItemTemplate><asp:TextBox ID="txtid5"runat="server"Text='<%#Eval("name")%>'></asp:TextBox></EditItemTemplate><FooterTemplate><asp:TextBox ID="txtid6" runat="server"></asp:TextBox></FooterTemplate></asp:TemplateField>  <asp:TemplateField HeaderText="Edit"><ItemTemplate><asp:LinkButton   ID="lnkbtn1"runat="server"CommandName="edit">edit</asp:LinkButton><asp:LinkButton ID="LinkButton1" runat="server" CommandName="delete">delete</asp:LinkButton></ItemTemplate><EditItemTemplate><asp:LinkButton ID="lnkbtn2" runat="server" CommandName="edit">edit</asp:LinkButton><asp:LinkButton ID="lnkbtn3" runat="server" CommandName="update">update</asp:LinkButton><asp:LinkButton ID="lnkbtn4" runat="server" CommandName="cancel">cancel</asp:LinkButton></EditItemTemplate><FooterTemplate><asp:LinkButton ID="lnkbtn5" runat="server" CommandName="ADD">ADD</asp:LinkButton></FooterTemplate></asp:TemplateField></Columns>        </asp:GridView>
```

![GridView Control in ASP.Net](https://www.mindstick.com/mindstickarticle/72e6f660-f985-4470-99d6-81f472882868/images/8d03797f-55ed-45dc-9bea-20be83ed8825.png)

## Bind Data in GridView:

Data will bind when [page loaded](https://www.mindstick.com/forum/515/clear-css-menu-hover-state-on-click-page-loaded-via-ajax).

```
protected void Page_Load(object sender, EventArgs e){ if (!Page.IsPostBack) {BindData();// this function is called when the page is loaded. }}    public void BindData(){// Here data is fetched from the database through stored procedure(insert_reg).   GridView1.DataSource = Class1.execute_spfill_grid("insert_reg");// Here data is bind to the control and show on page   GridView1.DataBind();}
```

\

In above code execute_spfill_grid is a function made in Class1.cs which is described below.

And insert_reg is a [stored procedure](https://www.mindstick.com/articles/36/stored-procedure-in-microsoft-sql-server) made in backend.This is described below

![GridView Control in ASP.Net](https://www.mindstick.com/mindstickarticle/72e6f660-f985-4470-99d6-81f472882868/images/2d221f2a-6bbf-4944-880a-84f0c0af57b7.png)

## GridView Event:

![GridView Control in ASP.Net](https://www.mindstick.com/mindstickarticle/72e6f660-f985-4470-99d6-81f472882868/images/5b753426-e042-49c0-8d91-92604e7a5522.png)

| RowEditing | Occurs when a row's Edit [button is clicked](https://answers.mindstick.com/qa/94813/why-does-my-app-terminate-when-the-button-is-clicked-on-android-studio), but before the GridView control enters edit mode. |
| --- | --- |
| RowCancelingEdit | Occurs when the Cancel button of a row in edit mode is clicked, but before the row exits edit mode. |
| RowCommand | Occurs when a button is clicked in a GridView control. |
| RowDeleting | Occurs when a row's Delete button is clicked, but before the GridView control deletes the row. |

**RowEditing event is used to enable editing in GridView**

```
protected void GridView1_RowEditing(object sender,  GridViewEditEventArgs e)    {         GridView1.EditIndex = e.NewEditIndex;         BindData();     }
```

**RowCancelingEdit event is used to cancel edit mode.**

```
      protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)    {         GridView1.EditIndex = -1;         BindData();    }
```

The zero-based index of the row to edit. EditIndex = -1, which indicates that no row is being edited.

![GridView Control in ASP.Net](https://www.mindstick.com/mindstickarticle/72e6f660-f985-4470-99d6-81f472882868/images/51e49f8f-f014-4a99-87be-d30e81c95a20.png)

**Update , Add and Delete data in gridview:**

Row updating event is used for updating data

```
protected void GridView1_RowUpdating(object sender,GridViewUpdateEventArgs e){// Here  FindControl will find the Id in which updating will be done. string i = ((Label)GridView1.Rows[e.RowIndex].Cells[0].FindControl("lblid1")).Text; string pas = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].FindControl("txtid3")).Text; string nm = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].FindControl("txtid5")).Text;Class1.update_reg_form("update_reg", i, pas, nm);// update_regform is a function which fetch the data from database through stored procedure(update_reg). GridView1.EditIndex=-1; BindData();}
```

The RowCommand event is raised whenever any button associated with a row in the **GridView** is clicked. This provides for programmatically determining which specific command button is clicked and take appropriate action.

**Here this event is used for Inserting data**

```
  protected void GridView1_RowCommand(object sender,GridViewCommandEventArgs e){ if (e.CommandName=="ADD") {// Here  FindControl will find the Id in which adding will be done.  string i = ((TextBox)GridView1.FooterRow.FindControl("txtid2")).Text;string pas = ((TextBox)GridView1.FooterRow.FindControl("txtid4")).Text;string nm = ((TextBox)GridView1.FooterRow.FindControl("txtid6")).Text;              Class1.ADD_reg_form("add_reg", i, pas, nm);GridView1.EditIndex = -1;BindData(); }}
```

**Row Deleting event is used to delete the data**

```
protected void GridView1_RowDeleting(object sender,GridViewDeleteEventArgs e){    string i = ((Label)GridView1.Rows[e.RowIndex].Cells[0].FindControl("lblid")).Text;Class1.DEL_reg_form("del_reg", i); GridView1.EditIndex = -1; BindData();}
```

\

![GridView Control in ASP.Net](https://www.mindstick.com/mindstickarticle/72e6f660-f985-4470-99d6-81f472882868/images/fd00767a-debc-4a33-b771-ea3f7cbe07a9.png)

Add both namespace in every .cs page in which you want to use data and SQL related keyword

```
using System.Data;using System.Data.SqlClient;
```

## \

## Class1.cs

```
using System;using System.Collections.Generic;using System.Linq;using System.Data;using System.Data.SqlClient;using System.Web; public class Class1{      // this function is used to bind data     public static DataSet execute_spfill_grid(string spname)    {          SqlConnection con = Connection.CreateConnection();          DataSet ds = new DataSet();          SqlCommand cmd = new SqlCommand();         cmd.CommandText = spname;         cmd.CommandType = CommandType.StoredProcedure;         cmd.Connection = con;         con.Open();         SqlDataAdapter da = new SqlDataAdapter(spname,con);         da.Fill(ds);              return ds;           }       public static void update_reg_form(string spname, string id, string pass, string name) // this function is used to update data    {         SqlConnection con = Connection.CreateConnection();                 SqlCommand cmd = new SqlCommand();         cmd.CommandText = spname;         cmd.CommandType = CommandType.StoredProcedure;         cmd.Parameters.Add("@id", SqlDbType.VarChar).Value = id;         cmd.Parameters.Add("@pass", SqlDbType.VarChar).Value = pass;         cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = name;          cmd.Connection = con;         con.Open();                 cmd.ExecuteNonQuery();         con.Close();    }      public static void ADD_reg_form(string spname, string id, string pass, string name)// this function is used to Add data    {         SqlConnection con = Connection.CreateConnection();          SqlCommand cmd = new SqlCommand();         cmd.CommandText = spname;         cmd.CommandType = CommandType.StoredProcedure;         cmd.Parameters.Add("@id", SqlDbType.VarChar).Value = id;         cmd.Parameters.Add("@pass", SqlDbType.VarChar).Value = pass;         cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = name;          cmd.Connection = con;         con.Open();          cmd.ExecuteNonQuery();         con.Close();    }      public static void DEL_reg_form(string spname, string id)// this function is used to Delete data    {         SqlConnection con = Connection.CreateConnection();          SqlCommand cmd = new SqlCommand();         cmd.CommandText = spname;         cmd.CommandType = CommandType.StoredProcedure;         cmd.Parameters.Add("@id", SqlDbType.VarChar).Value = id;                 cmd.Connection = con;         con.Open();          cmd.ExecuteNonQuery();         con.Close();    }} 
```

\

In class1.cs Connection keyword is used

Connection is class in whichCreateConnection function is created.

**Connection.cs**

```
using System;using System.Collections.Generic;using System.Linq;using System.Configuration;using System.Web;using System.Data;using System.Data.SqlClient;  public class Connection{        public static SqlConnection CreateConnection()    {         string connectionstring;         connectionstring = ConfigurationManager.ConnectionStrings["mycon"].ConnectionString;         SqlConnection sqlcon = new SqlConnection(connectionstring);         return sqlcon;    }      }
```

mycon is connection object created in web.config

**web.config:**

```
<connectionStrings>            <add name="mycon"connectionString="Data Source=(local);Initial Catalog=my; User Id=sa; Password=mindstick"providerName="System.Data.SqlClient"/>      </connectionStrings>
```

Write this [connection string](https://www.mindstick.com/articles/17/connection-string) above <system.web>

**Stored procedure:**

## This procedure is used to select data

```
Create procedure insert_reg  asbeginselect * from regformend
```

## \

**This procedure is used to [Insert data](https://www.mindstick.com/forum/172/how-v-insert-data-into-table-and-display-into-gridview-in-aspx-cs-file-with-out-using-wizard)**

```
Create procedure add_reg@id varchar(50),@pass varchar(50),@name varchar(50)asbegininsert into regform(id,pass,name)values(@id,@pass,@name)End
```

## \

**This procedure is used to [Delete data](https://www.mindstick.com/forum/34184/how-to-insert-update-delete-data-from-database-using-c-sharp)**

```
create procedure del_reg@id varchar(50)asbegindelete  from regform where id=@idend
```

## \

**This procedure is used to [Update data](https://www.mindstick.com/forum/380/how-achieve-batch-update-data)**

```
create procedure [dbo].[update_reg]@id varchar(50),@pass varchar(50),@name varchar(50)asbeginupdate regform set pass=@pass,name=@name where id=@idend
```

---

Original Source: https://www.mindstick.com/articles/184/gridview-control-in-asp-dot-net

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
