DotNetCurry Logo

GridView Tips and Tricks using ASP.NET – Part III

Posted by: Suprotim Agarwal , on 7/11/2008, in Category ASP.NET
Views: 179432
Abstract: The GridView control is quiet a handy control and is the most commonly used control when building an ASP.NET site. The more you work with it, the more you realize how powerful it can be while presenting data. Moving ahead with our GridView Tips and tricks series, I have added some more tips in this article.
GridView Tips and Tricks using ASP.NET – Part III
The GridView control is quiet a handy control and is the most commonly used control when building an ASP.NET site. The more you work with it, the more you realize how powerful it can be while presenting data.


Moving ahead with our GridView Tips and tricks series, I have added some more tips in this article. The previous two articles on the Tips and Tricks are mentioned below:
For this article, we would be using the following template to populate the GridView.
<html xmlns="" >
<head runat="server">
    <title>GridView Tips and Tricks Part 2</title>
    <form id="form1" runat="server">
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CategoryID"
            DataSourceID="SqlDataSource1" ShowFooter="true" AllowPaging="True" AllowSorting="True"
            PageSize="5" OnRowDataBound="GridView1_RowDataBound">
                <asp:TemplateField HeaderText="CategoryID" InsertVisible="False" SortExpression="CategoryID">
                        <asp:Label ID="lblCategoryID" runat="server" Text='<%# Bind("CategoryID") %>'></asp:Label>
                <asp:TemplateField HeaderText="CategoryName" SortExpression="CategoryName">
                        <asp:TextBox ID="txtCategoryName" runat="server" Text='<%# Bind("CategoryName") %>'></asp:TextBox>
                        <asp:Label ID="lblCategoryName" runat="server" Text='<%# Bind("CategoryName") %>'></asp:Label>
                <asp:TemplateField HeaderText="Description" SortExpression="Description">
                        <asp:TextBox ID="txtDesc" runat="server" Text='<%# Bind("Description") %>'></asp:TextBox>
                        <asp:Label ID="lblDesc" runat="server" Text='<%# Bind("Description") %>'></asp:Label>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=SUPROTIM;Initial Catalog=Northwind;Integrated Security=True"
            ProviderName="System.Data.SqlClient" SelectCommand="SELECT [CategoryID], [CategoryName], [Description] FROM [Categories]"
            UpdateCommand="UPDATE [Categories] SET [CategoryName] = @CategoryName, [Description] = @Description WHERE [CategoryID] = @CategoryID"/>
The web.config holding the connection will look similar to the following:
            <add name="NorthwindConnectionString" connectionString="Data Source =(local);Integrated Security = SSPI; Initial Catalog=Northwind;"/>
Tip 1: Change the color of a GridView Row based on some condition
    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
        if (e.Row.DataItem != null)
            DataRowView drv = (DataRowView)e.Row.DataItem;
            string catName = Convert.ToString(drv["CategoryName"]);
            if (catName.Trim() == "Confections")
                e.Row.BackColor = System.Drawing.Color.LightBlue;
      Protected Sub GridView1_RowCreated(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
            If Not e.Row.DataItem Is Nothing Then
                  Dim drv As DataRowView = CType(e.Row.DataItem, DataRowView)
                  Dim catName As String = Convert.ToString(drv("CategoryName"))
                  If catName.Trim() = "Confections" Then
                        e.Row.BackColor = System.Drawing.Color.LightBlue
                  End If
            End If
      End Sub
Tip 2: How to create an Image Command Field Column and add to the GridView at runtime
        if (!Page.IsPostBack)
            CommandField cmdField = new CommandField();
            cmdField.ButtonType = ButtonType.Image;
            cmdField.SelectImageUrl = "~/Images/Home_Np1.GIF";
            cmdField.ShowSelectButton = true;
            cmdField.HeaderText = "Select";
            If (Not Page.IsPostBack) Then
                  Dim cmdField As CommandField = New CommandField()
                  cmdField.ButtonType = ButtonType.Image
                  cmdField.SelectImageUrl = "~/Images/Home_Np1.GIF"
                  cmdField.ShowSelectButton = True
                  cmdField.HeaderText = "Select"
            End If
Tip 3: How to display images in the GridView from Filesystem based on an existing Column
Let us imagine that you have a folder ‘Images’ where you have stored images for each category. Eg: 1.GIF, 2.GIF, 3.GIF and so on. Now you want to display a different image based on each CategoryID. So for CategoryID = 1, the image is 1.GIF; for CategoryID=2, the image is 2.GIF and so on.
                        <asp:Image runat="server" ImageUrl='<%# "~/Images/"+ Eval("CategoryID") + ".GIF" %>' >
Tip 4: How to Retrieve Images from the database and display it in a GridView
I will assume that we have a image column called CatImg in the Categories table.
The first step would be to create an ImageHandler. In such scenarios such as the gridview, usually prefer to go in for a handler when I have to return binary data directly from the database. It gives more control on the resource returned. Moreover it is a preferred solution when you have to set the image programmatically.
To add a handler, right click project > Add New Item > Generic Handler > ShowImage.ashx. The code shown below, uses the Request.QueryString[“id”] to retrieve the CategoryID from it. The ID is then passed to the ‘ShowCatImage()’ method where the image is fetched from the database and returned in a MemoryStream object. We then read the stream into a byte array. Using the OutputStream.Write(), we write the sequence of bytes to the current stream and you get to see your image.
<%@ WebHandler Language="C#" Class="ShowImage" %>
using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;
public class ShowImage : IHttpHandler
    public void ProcessRequest(HttpContext context)
        Int32 catid;
        if (context.Request.QueryString["id"] != null)
            catid = Convert.ToInt32(context.Request.QueryString["id"]);
            throw new ArgumentException("No parameter specified");
        context.Response.ContentType = "image/jpeg";
        Stream strm = ShowCatImage(catid);
        byte[] buffer = new byte[4096];
        int byteSeq = strm.Read(buffer, 0, 4096);
        while (byteSeq > 0)
            context.Response.OutputStream.Write(buffer, 0, byteSeq);
            byteSeq = strm.Read(buffer, 0, 4096);
    public Stream ShowCatImage(int catid)
        string conn = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
        SqlConnection connection = new SqlConnection(conn);
        string sql = "SELECT catImg FROM Categories WHERE CategoryID = @ID";
        SqlCommand cmd = new SqlCommand(sql, connection);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@ID", catid);
        object img = cmd.ExecuteScalar();
            return new MemoryStream((byte[])img);
            return null;
    public bool IsReusable
            return false;
<%@ WebHandler Language="vb" Class="ShowImage" %>
Imports System
Imports System.Configuration
Imports System.Web
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Public Class ShowImage
      Implements IHttpHandler
      Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
            Dim catid As Int32
            If Not context.Request.QueryString("id") Is Nothing Then
                  catid = Convert.ToInt32(context.Request.QueryString("id"))
                  Throw New ArgumentException("No parameter specified")
            End If
            context.Response.ContentType = "image/jpeg"
            Dim strm As Stream = ShowCatImage(catid)
            Dim buffer As Byte() = New Byte(4095){}
            Dim byteSeq As Integer = strm.Read(buffer, 0, 4096)
            Do While byteSeq > 0
                  context.Response.OutputStream.Write(buffer, 0, byteSeq)
                  byteSeq = strm.Read(buffer, 0, 4096)
      End Sub
      Public Function ShowCatImage(ByVal catid As Integer) As Stream
            Dim conn As String = ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString
            Dim connection As SqlConnection = New SqlConnection(conn)
            Dim sql As String = "SELECT catImg FROM Categories WHERE CategoryID = @ID"
            Dim cmd As SqlCommand = New SqlCommand(sql, connection)
            cmd.CommandType = CommandType.Text
            cmd.Parameters.AddWithValue("@ID", catid)
            Dim img As Object = cmd.ExecuteScalar()
                  Return New MemoryStream(CType(img, Byte()))
                  Return Nothing
            End Try
      End Function
      Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
                  Return False
            End Get
      End Property
End Class
To access this image in the GridView based on the CategoryID, just add the following:
                        <asp:Image runat="server" ImageUrl='<%# "ShowImage.ashx?id=" + Eval("CategoryID") %>' >
Tip 5: How to programmatically enable/disable a control in the GridView when in the Edit Mode
If you want to quickly take a decision whether to enable or disable a control when the user edits the row, then use the Enabled attribute and set it to a method that returns a bool value:
<asp:TemplateField HeaderText="CategoryName" SortExpression="CategoryName">
                        <asp:TextBox ID="txtCategoryName" runat="server" Enabled='<%# EnableDisableTextBox() %>' Text='<%# Bind("CategoryName") %>'></asp:TextBox>
                        <asp:Label ID="lblCategoryName" runat="server" Text='<%# Bind("CategoryName") %>'></asp:Label>
    protected bool EnableDisableTextBox()
        if (1 == 1)
            return false;
      Protected Function EnableDisableTextBox() As Boolean
            If 1 = 1 Then
                  Return False
            End If
      End Function
You can test this code by adding a CommandField to the GridView as shown below
<asp:CommandField ButtonType="Link" ShowEditButton="true" /> 
Tip 6: How to insert an Image in between Rows of a GridView using ASP.NET
Please check my article on the same over here
Tip 7: How to loop through all the rows in all the pages of a GridView
One simple way to loop through all the rows in all the pages of a GridView is to access its DataSource. In this example, we will loop through the SQLDataSource to retrieve all the rows in a GridView and access its cell value. You can modify the logic depending on the type of controls you have added to the GridView
    protected void Button1_Click(object sender, EventArgs e)
        DataSourceSelectArguments dsaArgs = new DataSourceSelectArguments();
        DataView view = (DataView)SqlDataSource1.Select(dsaArgs);
        DataTable dt = view.ToTable();
        for (int i = 0; i < dt.Rows.Count; i++)
            for (int j = 0; j < dt.Columns.Count; j++)
                string s = dt.Rows[i][j].ToString();
       Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
            Dim dsaArgs As DataSourceSelectArguments = New DataSourceSelectArguments()
            Dim view As DataView = CType(SqlDataSource1.Select(dsaArgs), DataView)
            Dim dt As DataTable = view.ToTable()
            For i As Integer = 0 To dt.Rows.Count - 1
                  For j As Integer = 0 To dt.Columns.Count - 1
                        Dim s As String = dt.Rows(i)(j).ToString()
                  Next j
            Next i
       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.
If you liked the article,  Subscribe to my RSS Feed or Subscribe Via Email
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on Google+
Further Reading - Articles You May Like!
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook

Page copy protected against web site content infringement 	by Copyscape

Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Arjunan on Tuesday, July 22, 2008 9:59 AM
This is web page is very clever,
Comment posted by Tariq on Tuesday, July 22, 2008 4:33 PM
Comment posted by Ishita on Saturday, August 9, 2008 7:51 AM
Very helpful codes...

i have another problem related to the gridview..can u pls help me with the same...
i want to divide the columns in my grid into 2 subcolumns dynamically, how do i do it??
Comment posted by John on Thursday, September 11, 2008 3:57 AM
Correct me if i'm wrong but i thought you would be looping on the GridView itself and not on the DataTable based on your "Tip 7: How to loop through all the rows in all the pages of a GridView"

Other than that excellent work! Thanks a lot.
Comment posted by Suprotim Agarwal on Thursday, September 11, 2008 8:11 AM
John: Thanks for yur comment. I have observed that if you loop through the GridView, you are able to loop through the rows only for 'that current page'. Using the technique I have described, you can loop through the rows in 'all the pages' of the GridView.
Comment posted by AKV-Kanthavel on Tuesday, September 16, 2008 8:58 PM
How can i display the image in dynamically on my homepage using using
Comment posted by Suprotim Agarwal on Wednesday, September 17, 2008 8:24 AM
AKV: Check this article of mine to load images dynamically
Comment posted by Nirav on Tuesday, October 7, 2008 3:50 AM
Hi Suprotim
I wanted to use gridview for one of my web-form.But problem is
it requires user to add rows by just typing in grid columns and on click of save button outside/inside grid I want to save data.By searching I found that direct add functionality is not available.I am confused.I dont know what to do.Please help
Comment posted by Suprotim Agarwal on Tuesday, October 7, 2008 1:21 PM
Nirav: I have covered this in Tip 1: over here
Comment posted by Nirav on Wednesday, October 8, 2008 2:09 AM
I had checked that but my problem is I don't want to save the data to database until user clicks save button outside grid.
If user wants to more than one row then he should be allowed by clicking buttonfield.
Comment posted by Suprotim Agarwal on Thursday, October 9, 2008 5:57 AM
Nirav: You can use the OnRowUpdating event as shown here
Comment posted by Kalpesh on Monday, October 13, 2008 9:18 AM
Hello Sir
I am using grid I am bounding it on codebehind with select query.For edit I had taken command field.When I click edit update and cancel commands are visible but when I change values and press update the textboxe in footertemplate are still visible.alos the update and cancel button are visible.I am using grid for the first time.I am confused in editing and updating.I am not getting what to write on which event.
Comment posted by Suprotim Agarwal on Wednesday, October 15, 2008 1:02 AM
Kalpesh: Check out Tip 1 in the link given below which covers edit, update and delete
Comment posted by Carlos antonio garcia on Sunday, October 26, 2008 10:54 AM
very good!
Comment posted by varsha on Friday, November 21, 2008 1:43 AM
The article was Excellent
In this I have to show the same image but large onmouseover so how can I do that

Comment posted by David Jones on Monday, December 22, 2008 11:36 AM
I can't get image to show up for tip 4. please help.
Comment posted by e-statik on Monday, March 16, 2009 3:43 AM
Thx for this article.
I have a question about tip #4 (Retrieve Images from the database). You place the code that retrieves the image data from db into ShowCatImage function. But is it good for performance? If i have 100 rows in gridview it will create connection 100 times also. Isn't it?
Comment posted by Summer on Friday, April 3, 2009 12:57 PM
Thank you, very helpful!
Comment posted by Vlad on Wednesday, April 8, 2009 2:25 PM
Thank you for the good article!
Comment posted by Miney on Wednesday, June 8, 2011 12:57 PM
First I want to tell you Thanks alot for this great Website.As student I see this website very useful.. Second>> I have a point about ==>>Tip 1: Change the color of a GridView Row based on some condition>>? I wonder if I can Select multi Row depend on array
Like that
                     If catName.Trim() = Array(i) Then
                        e.Row.BackColor = System.Drawing.Color.LightBlue
                  End If
Comment posted by dhaval on Tuesday, January 31, 2012 12:34 PM
can you give me step by step implementation of editable grid view
Comment posted by Learn New on Tuesday, November 12, 2013 10:23 AM
Normally in gridivew, All buttons are enabled (Edit, Update or Cancel)

Is it possible to force the user to Click on Update/Cancel button, when in Record Edit Mode. ? and then to Click on Edit for other rows.