Some More GridView Tips and Tricks using ASP.NET - Part II

Posted by: Suprotim Agarwal , on 5/18/2008, in Category ASP.NET
Views: 80594
Abstract: In one of our previous articles 'GridView Tips and Tricks using ASP.NET 2.0', we discussed ten of the most frequently asked questions about the GridView control. This article adds ten more tips and tricks to our collection, related to the GridView control.
Some More GridView Tips and Tricks using ASP.NET - Part II
 
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.
In one of our previous articles GridView Tips and Tricks using ASP.NET 2.0, we discussed ten of the most frequently asked questions about the GridView control. This article adds ten more tips and tricks to our collection, related to the GridView control.

 

[Update: The 3rd part of the GridView Tips and Tricks can be found over here: GridView Tips and Tricks using ASP.NET - Part III  ]
For this article, we would be using the following template to populate the GridView.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>GridView Tips and Tricks Part 2</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CategoryID"
            DataSourceID="SqlDataSource1" ShowFooter="true" AllowPaging="True" AllowSorting="True"
            PageSize="5" OnRowDataBound="GridView1_RowDataBound">
            <Columns>                       
                <asp:TemplateField HeaderText="CategoryID" InsertVisible="False" SortExpression="CategoryID">
                    <ItemTemplate>
                        <asp:Label ID="lblCategoryID" runat="server" Text='<%# Bind("CategoryID") %>'></asp:Label>
                    </ItemTemplate>                  
                </asp:TemplateField>
                <asp:TemplateField HeaderText="CategoryName" SortExpression="CategoryName">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtCategoryName" runat="server" Text='<%# Bind("CategoryName") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblCategoryName" runat="server" Text='<%# Bind("CategoryName") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Description" SortExpression="Description">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtDesc" runat="server" Text='<%# Bind("Description") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblDesc" runat="server" Text='<%# Bind("Description") %>'></asp:Label>
                    </ItemTemplate>                               
                </asp:TemplateField>               
            </Columns>
        </asp:GridView>
        <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"/>
    </div>
    </form>
</body>
</html>
The web.config holding the connection will look similar to the following:
<configuration>
      <appSettings/>
      <connectionStrings>
            <add name="NorthwindConnectionString" connectionString="Data Source =(local);Integrated Security = SSPI; Initial Catalog=Northwind;"/>
      </connectionStrings>
...
</configuration>
Tip 1: Enable Disable Controls inside a GridView
There are at times when you have to disable controls on some rows, when a certain condition is satisfied. In this snippet, we will see how to disable editing for rows that have the CategoryName as ‘Confections’. Use the following code:
C#
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.DataItem != null)
            {
                Label lblControl = (Label)e.Row.Cells[2].FindControl("lblCategoryName");
 
                if(lblControl.Text == "Confections")
                {
                    e.Row.Cells[0].Enabled = false;
                }
            }
        }
    }
VB.NET
 Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
            If e.Row.RowType = DataControlRowType.DataRow Then
                  If Not e.Row.DataItem Is Nothing Then
                        Dim lblControl As Label = CType(e.Row.Cells(2).FindControl("lblCategoryName"), Label)
 
                        If lblControl.Text = "Confections" Then
                              e.Row.Cells(0).Enabled = False
                        End If
                  End If
            End If
 End Sub
 
Tip 2: Adding Arrows for Sorting Columns in a GridView
When you are sorting the columns in a GridView, it would be a nice to have feature, to display arrows which depict either an ascending or descending sort as shown below. Create a folder called ‘images’ and add two small images called up.gif and down.gif:
C#
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            foreach (TableCell cell in e.Row.Cells)
            {
                if (cell.HasControls())
                {
                        LinkButton btnSort = (LinkButton)cell.Controls[0];
                        Image image = new Image();
                        if (btnSort.Text == GridView1.SortExpression)
                        {
                            if (GridView1.SortDirection == SortDirection.Ascending)
                            {
                                image.ImageUrl = "images/up.gif";                          }
                            else
                            {
                                image.ImageUrl = "images/down.gif";    
                            }
                        }
                        cell.Controls.Add(image);
                    
                }             
            }
VB.NET
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.Header Then
            For Each cell As TableCell In e.Row.Cells
                  If cell.HasControls() Then
                        Dim btnSort As LinkButton = CType(cell.Controls(0), LinkButton)
                        Dim image As Image = New Image()
                        If btnSort.Text = GridView1.SortExpression Then
                        If GridView1.SortDirection = SortDirection.Ascending Then
                              image.ImageUrl = "images/up.gif"
                              Else
                              image.ImageUrl = "images/down.gif"
                              End If
                        End If
                        cell.Controls.Add(image)
                  End If
            Next cell
Tip 3: How to Add a Row Number to the Gridview
There are a couple of ways to do this. However I will share a very handy tip that was shared by XIII in the asp.net forums.
Just add the following tags to your <columns> section of your GridView
<asp:TemplateField>
    <ItemTemplate>
        <%# Container.DataItemIndex + 1 %>
    </ItemTemplate>
</asp:TemplateField>
Tip 4: How to programmatically hide a column in the GridView
There are two conditions to be checked in the Page_Load to hide a columns in the GridView, let us say the 3rd column:
If ‘AutoGenerateColumns’ = True on the GridView
C#
       GridView1.HeaderRow.Cells[2].Visible = false;
        foreach (GridViewRow gvr in GridView1.Rows)
        {
            gvr.Cells[2].Visible = false;
        }
VB.NET
         GridView1.HeaderRow.Cells(2).Visible = False
            For Each gvr As GridViewRow In GridView1.Rows
                  gvr.Cells(2).Visible = False
            Next gvr
If ‘AutoGenerateColumns’ = False on the GridView
C#
GridView1.Columns[2].Visible = false;
VB.NET
GridView1.Columns(2).Visible = False
Tip 5: Handling Concurrency Issues in GridView
If you are using the SqlDataSource (or ObjectDataSource), you can use both the SqlDataSource.ConflictDetection and OldValuesParameterFormatString property to handle concurrency issues. These two properties together control how to perform updates and delete operations when the underlying data source changes, while the operation is being carried out. The original and modified versions of each column can be tracked using the two properties.
Read more about it over here.
Tip 6: How to transfer multiple values from GridView to a different page
Check my article over here:
Tip 7: Displaying Empty Data in a GridView
When there are no results returned from the GridView control’s data source, the short and simple way of displaying a message to the user, is to use the GridView’s EmptyDataText property.  
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CategoryID"
            DataSourceID="SqlDataSource1" EmptyDataText="No data available"
            ShowFooter="true" AllowPaging="True" AllowSorting="True"
            PageSize="5" OnRowDataBound="GridView1_RowDataBound">
Note: You can also add style to the EmptyDataText by using the EmptyDataRowStyle property.
Tip 8: Displaying an Image in case of Empty Data in a GridView
As an alternative to using the EmptyDataText property, if you need to display an image or any HTML/ASP.NET control, you can use the EmptyDataTemplate. In this snippet below, we are using the image control in the <EmptyDataTemplate> to display an image.
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CategoryID"
            DataSourceID="SqlDataSource1" ShowFooter="true" AllowPaging="True" AllowSorting="True"
            PageSize="5" OnRowDataBound="GridView1_RowDataBound">
 
            <EmptyDataTemplate>
              <asp:Image id="imgNoData"
                ImageUrl="~/images/NoDataFound.jpg"
                AlternateText="No data found"
                runat="server"/>
           
            </EmptyDataTemplate>
Tip 9: Highlight a Row in GridView without a PostBack
Check my article on the same over here:
Tip 10: How to Bind a List<> to a GridView
Let us see how to bind a List<> to a GridView. We assume that the ‘AutoGenerateColumns’ = True. We will create a class called Employees and bind it to the GridView with the help of a List<>.
Create a class called ‘Employees’
C#
public class Employee
{
    private string enm;
    private int ageofemp;
    private string department;
 
    public string EName
    {
        get
        {
            return enm;
        }
        set
        {
            enm = value;
        }
    }
 
    public int Age
    {
        get
        {
            return ageofemp;
        }
        set
        {
            ageofemp = value;
        }
    }
 
    public string Dept
    {
        get
        {
            return department;
        }
        set
        {
            department = value;
        }
    }
 
    public Employee(string ename, int age, string dept)
    {
        this.enm = ename;
        this.ageofemp = age;
        this.department = dept;
    }
 
 
}
 
VB.NET
Public Class Employee
      Private enm As String
      Private ageofemp As Integer
      Private department As String
 
      Public Property EName() As String
            Get
                  Return enm
            End Get
            Set(ByVal value As String)
                  enm = value
            End Set
      End Property
 
      Public Property Age() As Integer
            Get
                  Return ageofemp
            End Get
            Set(ByVal value As Integer)
                  ageofemp = value
            End Set
      End Property
 
      Public Property Dept() As String
            Get
                  Return department
            End Get
            Set(ByVal value As String)
                  department = value
            End Set
      End Property
 
      Public Sub New(ByVal ename As String, ByVal age As Integer, ByVal dept As String)
            Me.enm = ename
            Me.ageofemp = age
            Me.department = dept
      End Sub
 
 
End Class
 
Bind the ‘Employee’ data to the GridView using a List<>
C#
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Collections.Generic.List<Employee> emp = new System.Collections.Generic.List<Employee>();
        emp.Add(new Employee("Jack", 22, "Marketing"));
        emp.Add(new Employee("Anna", 28, "Advertising"));
        emp.Add(new Employee("Linra", 23, "Advertising"));
        emp.Add(new Employee("Jacob", 44, "Production"));
        emp.Add(new Employee("Zinger", 28, "PPC"));
 
        GridView1.DataSource = emp;
        GridView1.DataBind();
 
 
    }
VB.NET
      Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
            Dim emp As System.Collections.Generic.List(Of Employee) = New System.Collections.Generic.List(Of Employee)()
            emp.Add(New Employee("Jack", 22, "Marketing"))
            emp.Add(New Employee("Anna", 28, "Advertising"))
            emp.Add(New Employee("Linra", 23, "Advertising"))
            emp.Add(New Employee("Jacob", 44, "Production"))
            emp.Add(New Employee("Zinger", 28, "PPC"))
 
            GridView1.DataSource = emp
            GridView1.DataBind()
 
 
      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
 
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, DNC .NET Magazine, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls. and is authoring another one at The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by obul on Monday, June 2, 2008 3:27 AM
gridview tips
Comment posted by Sreeram on Tuesday, June 10, 2008 2:27 AM
hi guys, its very useful for us.. v can get clear knowledge about gridview in asp.net.. my rating for this articles is excellent..
Comment posted by Kamal on Friday, June 27, 2008 1:27 AM
good article.

Can you explain more on List<> ? And i want to know how to use List<> on site based.

Comment posted by Suprotim Agarwal on Friday, June 27, 2008 7:08 AM
Sreeram: Thanks

Kamal: Check this link:
http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx
Comment posted by swapna on Friday, July 4, 2008 8:19 AM
i got more idea about gridview by read this article....
thnks
Comment posted by sahil mohali on Monday, July 7, 2008 7:34 AM
Nice article , it is very useful for us like freshers.
Comment posted by md mashooque ali on Monday, July 7, 2008 8:37 AM
it is very nice and i really got help from this codeing
thanks buddy for this!!!!!!
Comment posted by Roger on Friday, September 5, 2008 10:45 AM
Nice set of articles!

I am currently looking for a way to get null values to show the same way in a templatefield as they do in a boundfield.  With templatefield, the box around the empty cell does not appear when data is null or empty string.

Other quirk is that when setting background color of boundfield, the whole cell is affected, with templatefield, only the background of text itself is shown.
Comment posted by Suprotim Agarwal on Saturday, September 6, 2008 12:08 AM
Roger: Thanks. Something similar should do the trick

<ItemTemplate>
<%# (null == Eval("CustID")) ? string.Empty : Convert.ToString(Eval("CustID") %>
</ItemTemplate>
Comment posted by James Wang on Sunday, December 21, 2008 12:51 PM
does tip 2 work?

Many tips here just don't work or missing a critical element.  Misleading information is worse than no information!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Comment posted by Suprotim Agarwal on Friday, December 26, 2008 9:12 PM
James: All the tips have been tested. They do work!!
Comment posted by James Wang on Wednesday, December 31, 2008 3:54 PM
if anyone try tip, you will need move this line of code:
cell.Controls.Add(image);
inside the
                        if (btnSort.Text == GridView1.SortExpression)
                        {
                        }
statement.
Comment posted by Suprotim Agarwal on Thursday, January 1, 2009 11:18 AM
James: Thanks again for your comment. Let me test this again and get back to you. Keep the feedback coming!
Comment posted by Websaint on Friday, August 14, 2009 6:00 AM
I jave a challenge with this gridview i want to display data on the gridview based on a textbox date selections between two date ranges in textBox1 and textBox2.can somebody salvage me here the gridview refuse to display.I will appreciate a tidy code to that effect.
Comment posted by Suprotim Agarwal on Saturday, August 15, 2009 2:41 AM
WebSaint: A quick solution is to create ControlParameters in your <SelectParameters> collection and then use it in your query to Filter out data. check an example here
http://forums.asp.net/p/1114949/1730465.aspx
Comment posted by bandaru.gopal@gmail.com on Tuesday, November 10, 2009 12:17 AM
ineed password for suscribeed downloaded articles
Comment posted by Pradip on Wednesday, February 10, 2010 5:12 AM
This is Good

http://pradipyadav.blogspot.com
Comment posted by Brandon on Tuesday, August 3, 2010 11:29 PM
I love these, thanks!  The only problem I see for the arrows with sorting (Tip 2) is that it relies on the caption being the same as the sort expression.  Usually you change the display caption to be something kinder to the user.  Any hints on how to get it to work when the grid column HeaderText <> SortExpression?
Comment posted by bbb on Tuesday, September 9, 2014 7:39 AM
OK

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel