How do I wrap header text if my data source is a DataTable?

708 Views Asked by At

I have a GridView whose data source is built dynamically as a DataTable - how can I specify column-specific header wrapping considering I'm specifying the structure in code?

I've not found anything to deal with this specific situation as I need to wrap only some columns in specific places, e.g. wrapping the second column below after 'Long' but leaving others alone. Adding \n or <br /> don't work as they're just treated as literals.

var statsTable = new DataTable();
statsTable.Columns.Add("Run Date", typeof(DateTime));
statsTable.Columns.Add("Needlessly Long Test Header", typeof(string));
...etc

statsTable.Rows.Add(runDate, "example", ...)

gridView.DataSource = statsTable;
gridView.DataBind();

Not sure if this is relevant, but I've found that I need to keep AutoGenerateColumns = true on my GridView otherwise nothing shows up. This is confusing me as I thought specifying the columns would do the trick - if this is unrelated to this question I'll ask another later.

Using .Net 3.5, if that affects answers. It seems like it'd be a simple/common problem.

2

There are 2 best solutions below

2
Razvan Trifan On

You could use a custom class to achieve that:

class CustomDataRow
{
    public string ColumnHeader { get; set; }
    public string ColumnName { get; set; }
    public string ColumnValue { get; set; }
}

Then, instead of a DataTable, you could use a List to bind the grid. Then, in the ItemDataBound event you could cast the DataItem to a CustomDataRow. If e.Item.ItemType is header, set the header text. If it's an item, set the Text values.

0
James Johnson On

Give something like this a shot:

Markup:

<asp:TemplateField>
    <HeaderTemplate>
        <%#HttpUtility.HtmlDecode(InsertBreaks(Eval("DataField")))%>
    </HeaderTemplate>
</asp:TemplateField>

With a LiteralControl:

<asp:TemplateField>
    <HeaderTemplate>
        <asp:Literal ID="litHeader" Text='<%#HttpUtility.HtmlDecode(InsertBreaks(Eval("DataField")))%>' Mode="PassThrough"></asp:Literal>
    </HeaderTemplate>
</asp:TemplateField>

Code-behind:

protected string InsertLineBreaks(string val)
{
    return val.Replace("long", "long<br/>").replace("foo", "foo<br/>");
}