Adding glyphs to a GridViewa

In Dino Esposito’s GREAT book for ASP.NET 2.0 called Introducing Microsoft ASP.NET 2.0, he gives a good hint for adding the little up/down arrows (glyphs) to a gridview to indicate sorting direction. Well, unfortunately, he wrote the book using Beta 1 of the 2.0 Framework, and Beta 1 of VS2005. Now that we’re very near RTM, and one of his commands was made obsolete in Beta2, I had to do a little editing to it.

So, his original code:

void AddGlyph(GridView grid, GridViewRow item)
{
Label glyph= new Label();
glyph.EnableTheming = false;
glyph.Font.Name = “Webdings”;
glyph.Font.Size = FontUnit.XSmall;
glyph.Text = (grid.SortDirection==SortDirection.Ascending ?” 5″ : ” 6″);

//Find the column you sorted by
for(int i=0; i < grid .Columns.Count; i++)
{
string colExpr = grid.ColumnFields[i].SortExpression;
if(colExpr != “” && colExpr == grid.SortExpression)
item.Cells[i].Controls.Add(glyph);
}
}

There are a couple of issues with that though. The ColumnFields collection has been depricated as of Beta2, meaning it must be replaced with Columns instead. So I did that. And it worked, sometimes. On some of my grids, I would an error that the Index was out of range for the collection. After thinking about it I realized that the Items.Cells collection was not necessarily the same as the grid.Columns collection. Yeah, in a perfect world it would be, but if you’re hiding columns (like I do to make the grid more usable), then it is different. So I rewrote the for loop as follows: 

for(int i=0; i< item.Cells.Count; i++)
{
string colExpr = grid.Columns[i].SortExpression;
if(colExpr != “” && colExpr == grid.SortExpression)
item.Cells[i].Controls.Add(glyph);
}

Note that you still have to use the grid.Columns to evaluate the Sort Expression, but instead of counting the grid columns, we’re counting against the row’s cell collection.

And now, no more errors! 

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

About the author

riceboyler is the pseudonym of one Jason Clark, an IT guy who does ASP.NET and Windows Phone development from time to time, waxes poetic about VMWare, Netapp and Dell, and quite frequently posts things that have nothing to do with computers, but deal with life as a father, husband, Webelos Leader and Latter-day Saint.

Follow him on Twitter at @riceboyler.

Month List