Thursday, March 3, 2011

Is there any way to get a DetailsView control to render its HeaderText in a <th> cell?

As the DetailsView uses <td> cells for both the header text and the data, I was wondering whether the behaviour of the control can be overridden to render the HeaderText of each row in a <th> cell?

From stackoverflow
  • There's no option built into the control itself. However, you can completely override the render behavior for any control, including DetailsView, by using a Control Adapter.

  • @Joel Coehoorn Thanks for the quick reply, but I was kind of hoping I wouldn't have to go down that route.

    I was wondering whether it would be possible to override one of the control rendering methods to achieve this?

    Someone seems to have had success rendering <th> cells but did not appear to disclose details - any other suggestions would be gratefully received.

  • I managed to find a way around this by using the ItemCreaed event handler and swapping the <td> cell for a <th> cell like this:

    if (view.Rows.Count > 0) {
        // swap each header <td> cell for a <th> cell
        foreach (DetailsViewRow row in view.Rows) {
            if (row.RowType == DataControlRowType.DataRow) {
                DataControlFieldCell td = row.Cells[0] as DataControlFieldCell;
                // skip the last row that contains our command controls
                if (td.Controls.Count > 0) {
                    continue;
                }
    
                DataControlFieldHeaderCell th = new DataControlFieldHeaderCell(td.ContainingField);
                th.Text = td.Text;
                th.Attributes.Add("scope", "row");
    
                // add the new th and remove the old td
                row.Cells.RemoveAt(0);
                row.Cells.AddAt(0, th);
            }
        }
    }
    
  • You could also inherit your own custom control from DetailsView, and then override the render method.

0 comments:

Post a Comment