22

In HTML in the td of a table you can break text by using <BR> between the words. This also works in the HeaderText of a TemplateItem but not the HeaderText of a BoundField. How do I break up the Header text of a BoundField.

AakashM
  • 62,551
  • 17
  • 151
  • 186
minty
  • 22,235
  • 40
  • 89
  • 106
  • You can use NewLine (not BR) and white-space: pre-line css as suggested in [How to properly display line breaks in asp GridView BoundField without turning HTML encoding off](//stackoverflow.com/q/44467086) – Michael Freidgeim Oct 01 '19 at 04:33

2 Answers2

37

Set HtmlEncode = false inside the BoundField

 <asp:BoundField DataField="SomeDataField" 
        HeaderText="SomeHeader<br />(OtherData)" 
        HtmlEncode="false" />

BoundField.HtmlEncode is true by default which means that if HTML is added in the text it will be encoded.
If HtmlEncode is set to false the text is not encoded and the br will work as expected. Unfortunately is not possible to specify this only for the header text, it will affect the cell contents as well.

naveen
  • 53,448
  • 46
  • 161
  • 251
Aleris
  • 7,981
  • 3
  • 36
  • 42
  • +1: i missed this little property and was looking for serious hacks. thanks :) – naveen Apr 21 '12 at 08:09
  • 1
    This will, of course, mess up the actual field text display (if it has things that look like HTML, including `&`), so beware. Especially if the grid displays user-supplied data, because you're opening yourself up for an injection attack. – Roman Starkov Nov 28 '14 at 16:36
  • HtmlEncode="false" is not recommended due to potential XSS attacks https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.boundfield.htmlencode?view=netframework-4.8 – Michael Freidgeim Oct 01 '19 at 04:18
2

For those of you trying to do this without disabling HtmlEncode it's pretty simple, if a little silly looking. Just use a real line break. Like so...

<asp:BoundField DataField="ProposedExtractionStartDate" HeaderText="Proposed
                        Extraction Start Date" SortExpression="ProposedExtractionStartDate"  DataFormatString="{0:MM/dd/yyyy}" />

That will actually come out as multi-line when the HTML renders.

If there is a character combination that will signify this, I would love to know it.

Tom Padilla
  • 924
  • 10
  • 30
  • I didn't test with the front end tag, but if defining a `BoundField` from the code-behind, I successfully got the text to break with `\n\r`. – GoldDragonTSU Sep 27 '22 at 21:40