Problem:

You want to display HTML formatted content in a GridView, but HTML tags are escaped and visible in the browser. As far as I know, the GridView BoundField is the only field that does a .HtmlEncode.

Solution:

  1. .HtmlDecode the text in each cell on RowDataBound
    Something like:

    Sub gv_drb(sender As Object, e As GridViewRowEventArgs)
                                                Handles gv.RowDataBound
        For Each cell As TableCell In e.Row.Cells
            cell.Text = Server.HtmlDecode(cell.Text)
        Next
    End Sub

    This is not be the most efficient solution since each cell will be first encoded automatically and then decoded by you, but that overhead may be negligible.

    Note:

    • I learned here that: “Setting the Text property will clear any other controls contained in the TableCell.”
      So, with the above method, you would loose, for example, links and buttons in autogenerated update, select, etc. columns. For autogenerated columns it is sufficient to check if there is Text, since their Text property is empty:
      If cell.Text <> "" ...
    • You might want to limit the type of row to decode, i.e. not decoding header cells:
      If Not e.Row.RowType = DataControlRowType.Header...
  2. Other solutions I haven’t tried:

  3. Write a custom GridView control
    To prevent HTML encoding in the first place, override InitializeCell and set allowHtmlEncode=false. I have not tried that, more on the idea can be found at 4 Guys from Rolla.
  4. Use a DataGrid
    As mentioned before, htmlencoding is a GridView specific feature. If it is feasible, you could switch to a different control, like a DataGrid.

Problem:

Setting a column’s visible attribute to Visible="false" does not just visually hide the column, it actually removes the column when databinding, so that contained values are not accessible. This is a useful feature, but sometimes you do not want to display a field (for example ID numbers) and still need to use the value later in a row event.

Solutions:

  1. Hide the column after databinding .DataBind()
    If the column is visible at databinding, it will be created and stay accessible.
    Note: You might have to make sure that the column is visible=true before databinding on postbacks. It could look something like this:

    Me.gv.Columns(1).Visible = True
    Me.gv.DataBind()
    Me.gv.Columns(1).Visible = False

  2. Hide a column with CSS.
    This is easiest if you declared each column as <asp:BoundField CssClass=hidden ...>, but it could also be done programmatically. The css could look like this:

    .hidden { display:none;}.

    The visible colums might require CSS with display:block; to be displayed properly.

Follow

Get every new post delivered to your Inbox.