Thursday, October 23, 2008

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.

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:

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:

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

ForEach 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.

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.