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.

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:

Tip 2: How to create an Image Command Field Column and add to the GridView at runtime

C#

if (!Page.IsPostBack)

{

CommandField cmdField = newCommandField();

cmdField.ButtonType = ButtonType.Image;

cmdField.SelectImageUrl = "~/Images/Home_Np1.GIF";

cmdField.ShowSelectButton = true;

cmdField.HeaderText = "Select";

GridView1.Columns.Add(cmdField);

GridView1.DataBind();

}

VB.NET

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"

GridView1.Columns.Add(cmdField)

GridView1.DataBind()

EndIf

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.

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.

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