Ian Oxley
Ian Oxley

Reputation: 11056

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?


@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.

Upvotes: 1

Views: 1392

Answers (4)

Udi Azulay
Udi Azulay

Reputation: 1

inherit from DetailsView and paste the code. this eliminate the need to recreate the header cell (as suggested in Ian's answer)

protected override void InitializeRow(DetailsViewRow row, DataControlField field)
{
        if (row.RowType == DataControlRowType.DataRow && field.ShowHeader)
        {
            DataControlFieldCell cell = new DataControlFieldHeaderCell(field);
            field.InitializeCell(cell, DataControlCellType.Header, row.RowState, DataItemIndex);
            row.Cells.Add(cell);
            cell = new DataControlFieldCell(field);
            field.InitializeCell(cell, DataControlCellType.DataCell, row.RowState, DataItemIndex);
            row.Cells.Add(cell);
        }
        else base.InitializeRow(row, field);
}

Upvotes: 0

Joel Coehoorn
Joel Coehoorn

Reputation: 415880

You could also inherit your own custom control from DetailsView, and then override the render method.

Upvotes: 1

Ian Oxley
Ian Oxley

Reputation: 11056

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);
        }
    }
}

Upvotes: 3

Joel Coehoorn
Joel Coehoorn

Reputation: 415880

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.

Upvotes: 1

Related Questions