Wednesday, May 5, 2010

How To Sort With a Custom GridView ItemTemplate

I've been playing around a lot today with the GridView control and wanted to try to use it as a listing tool to show results from a search.

I would prefer to display the results in a stylized panel rather than the usual spreadsheet format. To accomplish this, I can use the <asp:TemplateField> column object and build any kind of HTML my heart desires:

<asp:TemplateField>
<ItemTemplate>
<div style="background-color: #e4e4e4; color: #303030; padding: 10px;">
<div>
<%#Eval("row_image")%>
</div>
<div>
<%#Eval("row_name")%>
</div>
<div>
<%#Eval("row_description")%>
</div>
<div>
<%#Eval("row_priceRange")%>
</div>
</div>
</ItemTemplate>
</asp:TemplateField>


Now, I want to use the GridView control's Sorting feature that is usually handled by the HeaderText. I want to allow users to sort by Name, Description and Price Range. I can create a a column for each of these fields that will also create HeaderText that I can then use for the SortExpression value:
<asp:TemplateField HeaderText="Name" SortExpression="row_name" />
<asp:TemplateField HeaderText="Description" SortExpression="row_description" />
<asp:TemplateField HeaderText="Price Range" SortExpression="row_priceRange" />

I used the TemplateField control rather than the BoundField so that I wouldn't actually populate any data into the field. It's just a header and a blank cell with the width of the HeaderText. This will create a lot of empty space to the right of my GridView which I don't want, plus the clickable Headers are way to the right of the GridView itself.

A little bit of CSS easily fixed the issue. I'll set my CssClass of the GridView to CssClass="gv_list" and add the following css structure:
.gv_list th {
float: left;
}

Now, I've got three links at the top of my GridView that I can use for sorting the content either Ascendingly or Descendingly. Just to make sure all my site visitors understand what the links are for, I'll add some HeaderText to my first column (with all the divs) HeaderText="Sort By" and we are golden.


0 comments:

Post a Comment