If HtmlEncode doesn’t work for WebDataGrid…

While working with Infragistics WebDataGrid/WebHierarchicalDataGrid I noticed a strange thing: column’s HtmlEncode property (which should control whether HTML value of grid’s cell is rendered as HTML or shown as is in raw tags) had no effect. Maybe I was doing something wrong, maybe it was the fact that grid columns were generated in server-side code (here is short snippet):

oGridCol = New GridControls.BoundDataField()
oGridCol.DataFieldName = sDataColName
oGridCol.Header.Text = sCaption
oGridCol.Key = sKey

if '(some condition) then
   oGridCol.HtmlEncode = False
   oGridCol.CssClass = "nowrapHTML"
   oGridCol.HtmlEncode = True
   oGridCol.CssClass = "nowrapPLAIN"
End If

Here if a certain condition is met – column should render HTML (HtmlEncode = False) otherwise it should display HTML tags (HtmlEncode = True). To make cell expand to data width, 2 simple CSS classes were used:

.nowrapHTML {white-space:nowrap}
.nowrapPLAIN {white-space:pre}

In following grid first column was being set with HtmlEncode = True, second with HtmlEncode = False, yet both columns were rendered as HTML.

HtmlEncode doesn't work

The solution I chose is pretty straightforward and a bit crude, but it works. In grid’s InitializeRow event I loop thru all the row’s cell. If cell content is supposed to be HTML encoded code actually calls Server.HtmlEncode function. It also replaces carriage returns with <br/> tags simulating line-breaks of plain text:

 Protected Sub xMyGrid_InitializeRow(ByVal sender As Object, _
    ByVal e As IGridControls.RowEventArgs) Handles xMyGrid.InitializeRow

   'HTML Encode hack
   For I As Integer = 0 To e.Row.Items.Count - 1
      With e.Row.Items(I)
         If CType(.Column, GridControls.BoundDataField).CssClass = _
            "nowrapPLAIN" Then
            .Text = Server.HtmlEncode(.Text).Replace(vbCrLf, "<br/>")
         End If
       End With

End Sub

I had to compare by CssClass name, because for some reason HtmlEncode property was reset back to TRUE for all columns. Here is the grid that was generated by this code:

HtmlEncode works

UPDATE 03/20/2012: This hack is no longer needed as of NetAdvantage version 2011.1 – Infragistics fixed the issue and columns HtmlEncode and EnableMultiline properties now work correctly.

3 replies on “If HtmlEncode doesn’t work for WebDataGrid…”

  1. @Roberto This is pretty much it, and the main part is in InitializeRow event. Have you tried it unconditionally to see if Server.HtmlEncode does the trick?

Leave a Reply

Your email address will not be published. Required fields are marked *