Yesterday I was working on a product list using the Gridview component and needed to render the list of products ordered by category. The list also had to have a subheading for the category of the product e.g.
It took a while to figure out but this article by Tim Heuer (there's a show/hide code at the bottom of the page) helped solve the problem. With a minor modification I got what I wanted.
I didn't require the sorting mechanism so I assigned the DataKeyNames property of the Gridview the names of the fields used to order the list before binding to the datasource so that I could pick out the category ID (line 71) in the controls overridden Render method:
1 protected override void Render(HtmlTextWriter writer)
2 {
3 Table table = (Table)this.productsGrid.Controls[0];
4
5 int lastCategory = -1;
6
7 foreach(GridViewRow row in productsGrid.Rows)
8 {
9 int realIndex = table.Rows.GetRowIndex(row);
10 int currentCategory = Convert.ToInt32(this.productsGrid.DataKeys[row.RowIndex].Values[1]);
11 if(currentCategory != lastCategory)
12 {
13 GridViewRow groupHeaderRow =
14 new GridViewRow(realIndex, realIndex, DataControlRowType.Separator, DataControlRowState.Normal);
15 TableCell newCell = new TableCell();
16 newCell.ColumnSpan = this.productsGrid.Columns.Count;
17 newCell.BackColor = System.Drawing.Color.FromArgb(233, 229, 229);
18 newCell.ForeColor = System.Drawing.Color.DarkGray;
19 newCell.Font.Bold = true;
20
21 switch(currentCategory)
22 {
23 case 515:
24 case 517:
25 newCell.Text = "Home Products";
26 break;
27
28 default:
29 newCell.Text = "Business Products";
30 break;
31 }
32
33 groupHeaderRow.Cells.Add(newCell);
34
35 table.Controls.AddAt(realIndex, groupHeaderRow);
36 lastCategory = currentCategory;
37 }
38 }
39
40 base.Render(writer);
41 }
Remember Me
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.