Friday, May 16, 2008

Filter icon in GridView

I was trying to do this the other day: display the filter icon on a gridview. Now when you do a sort an icon is displayed in the heading of the gridview as to whether it's an ascending or descending sort but there is no such default behaviour when filtering. Its a problem because you can't tell if a filter is applied or not unless an icon is displayed.

So here is the solution which you need to plug into the RowDataBound event. It involves checking the value of the FilterFieldname and if its not blank add an image control to the cell on which the filter is placed.

There is no need to have the alternate code to remove the filter as it seems to do this anyway. The image I was using for the filter comes from the images directory in MOSS 2007. I've displayed the image to the left of the header text which has a slightly better behaviour than putting it on the right. Below this text I show how to replace the priority icon with a symbol, again quite a common requirement.

void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
// show the filter icon
if (gridView.FilterFieldName != "")
{
int head = 0;
if (e.Row.RowType == DataControlRowType.Header)
{
for (int i = 0; i < colsNames.Length; i++)
{
if (colsNames[i].ToString().ToLower() == gridView.FilterFieldName.ToLower())
{
head = i ;
break;
}
}
Image img = new Image();
img.ImageUrl = "_layouts/images/ewr093.gif";
img.ImageAlign = ImageAlign.Left;
e.Row.Cells[head].Controls.Add(img);
}


}
// show the priority icon
// replace square brackets for img elemet with angle brackets
if ((e.Row.RowType == DataControlRowType.DataRow))
{
int index = 0;
for (int i = 0; i < colsNames.Length; i++)
{
if (colsNames[i].ToString().ToLower() == "priority")
{
index = i;
break;
}
}

string priority = e.Row.Cells[index].Text;
switch (priority)
{
case "High":
e.Row.Cells[index].Text = "[img src='../_layouts/images/urgent.gif']";
break;
case "Low":
e.Row.Cells[index].Text = "[img src='../_layouts/images/arrdowni.gif']";
break;
default:
e.Row.Cells[index].Text = "";
break;
}

}

}

1 comment:

Anand Chandawarkar said...

Hi Charles,
Indeed very useful and interesting. Thanks a ton for the tip.
Cheers,
Anand