How to render decoded HTML in a (i.e. a
) in G

2019-02-03 03:45发布

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?

9条回答
叼着烟拽天下
2楼-- · 2019-02-03 04:00

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

<asp:BoundField DataField="MyColumn" HtmlEncode="False" />
查看更多
forever°为你锁心
3楼-- · 2019-02-03 04:00
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{

    for (int i = 0; i < e.Row.Cells.Count; i++)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string decodedText = HttpUtility.HtmlDecode(e.Row.Cells[i].Text);
            e.Row.Cells[i].Text = decodedText;
        }
    }
}
查看更多
Root(大扎)
4楼-- · 2019-02-03 04:07

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
查看更多
Emotional °昔
5楼-- · 2019-02-03 04:10

You have to bind to the the DataBoundGrid event and change the Rendering for the columns you want to render HTML code.

public event EventHandler DataBoundGrid {
  add { ctlOverviewGridView.DataBound += value; }
  remove { ctlOverviewGridView.DataBound -= value; }
}

ctlOverview.DataBoundGrid += (sender, args) => {
  ((sender as ASPxGridView).Columns["YourColumnName"] as GridViewDataTextColumn).PropertiesTextEdit.EncodeHtml = false;
};
查看更多
仙女界的扛把子
6楼-- · 2019-02-03 04:15

@Ray Booysen answers is right but in some cases HtmlDecode() can't handle your problem. you can use UrlDecode() instead of HtmlDecode().
here is another solution:

if (e.Row.RowType == DataControlRowType.DataRow)
{
  string decodedText = HttpUtility.UrlDecode(e.Row.Cells[0].Text);
  e.Row.Cells[0].Text = decodedText;
}
查看更多
做个烂人
7楼-- · 2019-02-03 04:16

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.

查看更多
登录 后发表回答