Click here to Skip to main content
12,629,359 members (34,717 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


14 bookmarked

GridView Tips and Tricks using ASP.NET 2.0

, 18 Jul 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
A quick overview of some of the most frequently used features of the GridView control.

Tip 1: Add, Update, Delete Records in a GridView using SqlDataSource

By default, the GridView control doesn’t have support for inserting new records. However you can use the built-in edit or delete functionality of the GridView control. Let us explore how to insert new records and Update and Delete existing records in a GridView. Just copy and paste the code in your project. We will be using the ‘Categories’ table in the ‘Northwind’ database.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView.aspx.cs" Inherits="GridView" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 

<html xmlns="" >
<head runat="server">
    <title>Grid View Add Update Delete</title>
    <form id="form1" runat="server">
        <asp:GridView ID="GridView1" runat="server" 
            AutoGenerateColumns="False" DataKeyNames="CategoryID"
            DataSourceID="SqlDataSource1" ShowFooter="true" 
            AllowPaging="True" AllowSorting="True" OnRowCommand="GridView1_RowCommand">
                <asp:CommandField ShowDeleteButton="True" ShowEditButton="True"/>                
                <asp:TemplateField HeaderText="CategoryID" 
                         InsertVisible="False" SortExpression="CategoryID">
                        <asp:Label ID="Label1" runat="server" Text='<%# Eval("CategoryID") %>'></asp:Label>
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("CategoryID") %>'>


protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    SqlConnection conn = new SqlConnection(
        if (e.CommandName.Equals("New"))
            LinkButton btnNew = e.CommandSource as LinkButton;
            GridViewRow row = btnNew.NamingContainer as GridViewRow;
            if (row == null)
            TextBox txtCatName = row.FindControl("CategoryNameTextBox") as TextBox;
            TextBox txtDescription = row.FindControl("DescriptionTextBox") as TextBox;                
            SqlCommand cmd = new SqlCommand(
                "INSERT INTO [Categories] ([CategoryName], [Description]) VALUES (@CategoryName, @Description)",
            cmd.Parameters.AddWithValue("CategoryName", txtCatName.Text);
            if (cmd.ExecuteNonQuery() == 1)
    catch (Exception ex)



  <add name="NorthwindConnectionString" 
    connectionString="Data Source =.;Integrated Security = SSPI; Initial Catalog=Northwind;"/>

Tip 2: Paging and Sorting a GridView without Refreshing a Page

If you have created a GridView and have bound it to a data source control, you can avoid postback during sorting and paging by setting the EnableSortingAndPagingCallbacks property of the GridView to True.

Just remember that when you set the EnableSortingAndPagingCallbacks property to true, you cannot use Template Fields in the GridView.

Tip 3: Pop-up a Confirmation box before Deleting a Row in GridView

Add a template field and drop a button in it, using which the user will delete the record. In the OnClientClick event, call the confirm() function as mentioned below:

        <asp:Button ID="btnDel" runat="server" Text="Delete"
            OnClientClick="return confirm('Are you sure you want to delete the record?');" />

Tip 4: Display Details of the Row Selected in the GridView

Assuming you have a button called ‘Select’ in your GridView with CommandName ‘Select’, to find out the row clicked and display the row’s details, use this code:


private void GridView1_RowCommand(Object sender, 
         GridViewCommandEventArgs e)
    if (e.CommandName == "Select")
        int idx = Convert.ToInt32(e.CommandArgument);
        GridViewRow selrow = GridView1.Rows[idx];
        string fstCell  = selrow.Cells[0].Text;
        string scndCell = selrow.Cells[1].Text;
        // and so on
        // Thanks to Mark Rae (MVP) for pointing
        // the typo. Earlier it was Cells[1] and Cells [2]


Private Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
      If e.CommandName = "Select" Then
            Dim idx As Integer = Convert.ToInt32(e.CommandArgument)
            Dim selrow As GridViewRow = GridView1.Rows(idx)
            Dim fstCell As String = selrow.Cells(0).Text
            Dim scndCell As String = selrow.Cells(1).Text
            ' and so on
      End If
End Sub

Tip 5: Retrieve Details of the Row Being Modified in GridView


void GridView1_RowUpdated(Object sender, GridViewUpdatedEventArgs e)
    // Retrieve the row being edited.
    int index = GridView1.EditIndex;
    GridViewRow row = GridView1.Rows[index];

    // Retrieve the value of the first cell 
    lblMsg.Text = "Updated record " + row.Cells[1].Text;


Private Sub GridView1_RowUpdated(ByVal sender As Object, ByVal e As GridViewUpdatedEventArgs)
    ' Retrieve the row being edited.
    Dim index As Integer = GridView1.EditIndex
    Dim row As GridViewRow = GridView1.Rows(index)

    ' Retrieve the value of the first cell 
    lblMsg.Text = "Updated record " & row.Cells(1).Text
End Sub

Tip 6: Retrieve Details of the Row being Deleted in GridView

The ID of the row being deleted must be in the GridView.DataKeyNames collection.


protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    int ID = (int)GridView1.DataKeys[e.RowIndex].Value;
    // Query the database and get the values based on the ID


Protected Sub GridView1_RowDeleting(ByVal _
          sender As Object, ByVal e As GridViewDeleteEventArgs) 
    Dim ID As Integer = CInt(GridView1.DataKeys(e.RowIndex).Value) 
    ' Query the database and get the values based on the ID 
End Sub

Tip 7: Cancelling Update and Delete in a GridView

  • RowUpdating - Occurs when a row's Update button is clicked, but before the GridView control updates the row.
  • RowDeleting – Occurs when a row's Delete button is clicked, but before the GridView control deletes the row.


protected void gvDetail_RowUpdating(object sender, GridViewUpdateEventArgs e)
    e.Cancel = true;
void GridView1_RowDeleting(Object sender, GridViewDeleteEventArgs e)
    // Check for a condition and cancel the delete
    // There should be atleast one row left in the GridView
    if (GridView1.Rows.Count <= 1)
        e.Cancel = true;


Protected Sub gvDetail_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
   e.Cancel = True
End Sub
Private Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
    ' Check for a condition and cancel the delete
    ' There should be atleast one row left in the GridView
    If GridView1.Rows.Count <= 1 Then
          e.Cancel = True
    End If
End Sub

Tip 8: Paging and Sorting in GridView Without Using the DataSource Control

Original code author: Ryan Olshan.


<asp:GridView ID="gridView" OnPageIndexChanging="gridView_PageIndexChanging" 
OnSorting="gridView_Sorting" runat="server" />
private string ConvertSortDirectionToSql(SortDirection sortDireciton)
   string newSortDirection = String.Empty;
   switch (sortDirection)
      case SortDirection.Ascending:
         newSortDirection = "ASC";
      case SortDirection.Descending:
         newSortDirection = "DESC";
   return newSortDirection
protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
   gridView.PageIndex = e.NewPageIndex;
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
   DataTable dataTable = gridView.DataSource as DataTable;
   if (dataTable != null)
      DataView dataView = new DataView(dataTable);
      dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
      gridView.DataSource = dataView;


Private Function ConvertSortDirectionToSql(ByVal sortDireciton As SortDirection) As String
   Dim newSortDirection As String = String.Empty

   Select Case sortDirection
       Case SortDirection.Ascending
             newSortDirection = "ASC"

       Case SortDirection.Descending
             newSortDirection = "DESC"
   End Select

   Return newSortDirection
End Function

Protected Sub gridView_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
   gridView.PageIndex = e.NewPageIndex
End Sub

Protected Sub gridView_Sorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs)
   Dim dataTable As DataTable = TryCast(gridView.DataSource, DataTable)

   If Not dataTable Is Nothing Then
       Dim dataView As DataView = New DataView(dataTable)
       dataView.Sort = e.SortExpression & " " & ConvertSortDirectionToSql(e.SortDirection)

       gridView.DataSource = dataView
   End If
End Sub

Tip 9: Delete Multiple rows in a GridView

Check this article of mine over here.

Tip 10: Export GridView to Excel


protected void Button1_Click(object sender, EventArgs e)
    Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
    Response.Charset = String.Empty;
    Response.ContentType = "application/vnd.xls";
    System.IO.StringWriter sw = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);


Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
    Response.AddHeader("content-disposition", "attachment;filename=FileName.xls")
    Response.Charset = String.Empty
    Response.ContentType = "application/vnd.xls"
    Dim sw As System.IO.StringWriter = New System.IO.StringWriter()
    Dim hw As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(sw)
End Sub

Well, that was a quick overview of some of the most frequently used features of the GridView control. I hope you liked the article and I thank you for viewing it.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

ketan italiya
Web Developer DevRepublic,India
India India
No Biography provided

You may also be interested in...


Comments and Discussions

Questiond a asd a Pin
Member 822740424-Aug-13 0:14
memberMember 822740424-Aug-13 0:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.161205.3 | Last Updated 18 Jul 2013
Article Copyright 2013 by ketan italiya
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid