views:

1789

answers:

5

I'm binding a GridView to an LINQ query. Some of the fields in the objects created by the LINQ statement are strings, and need to contain new lines.

Apparently, GridView HTML-encodes everything in each cell, so I can't insert a <br /> to create a new line within a cell.

How do I tell GridView not to HTML encode the contents of cells?

Maybe I should use a different control instead?

+5  A: 

Can you subscribe to the RowDataBound event? If you can, you can run:

if (e.Row.RowType == DataControlRowType.DataRow)
{
  string decodedText = HttpUtility.HtmlDecode(e.Row.Cells[0].Text);
  e.Row.Cells[0].Text = decodedText;
}
Ray Booysen
+1  A: 

Are normal newlines preserved in output? If so, you can send the newlines, and use the css style white-space: pre, which would preserve newlines, spaces and tabs.

configurator
A: 

I got around this by first inserting the data into my sql-server table from a multi-line textbox using

   replace (txt = Replace(txt, vbCrLf,"<br />"))

Then I used Ray Booysen's solution to return it to my gridview:

Protected Sub grdHist_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdHist.RowDataBound

  Dim col1 As String = HttpUtility.HtmlDecode(e.Row.Cells(2).Text)

  e.Row.Cells(2).Text = col1

End Sub

DaamonTurne
A: 

Booysen's answer works but only for one column. If you run a loop in the RowDataBound event, you can substitute a variable for the [0] and have this work on each column if you want. Here's what I did:

protected void gridCart_RowDataBound(object sender, GridViewRowEventArgs e)
{
    for (int i = 1; i < 4; i++)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string decode = HttpUtility.HtmlDecode(e.Row.Cells[i].Text);
            e.Row.Cells[i].Text = decode;
        }
    }
}

Mine is deliberately started at 1 because of my data, but obviously it will work with whatever you need.

John
A: 

What about setting the HTMLEncode property to false? To me, this is much simpler.

<asp:BoundField DataField="MyColumn" HtmlEncode="False" />
Aaron Daniels