2009-01-10 51 views
24

我将GridView绑定到LINQ查询。由LINQ语句创建的对象中的一些字段是字符串,并且需要包含新行。如何在GridView单元格中呈现解码的HTML(即<br>)

显然,GridView对每个单元格中的所有内容都进行了HTML编码,因此我无法插入一个< br/>以在单元格内创建新行。

如何让GridView不要HTML编码单元格的内容?

也许我应该使用不同的控制来代替?

回答

37

您可以订阅RowDataBound事件吗?如果可以的话,你可以运行:

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

一个这种方法的优点超过设定`HtmlEncode`在`BoundField`属性`FALSE`的是,你可以添加HTML标签中的文本,并仍然使用数据的HTML编码。例如, `e.Row.Cells [0] .Text =“”+ e.Row.Cells [0] .Text +“”;` – beawolf 2014-12-19 07:04:33

3

正常的换行符保存在输出中吗?如果是这样,您可以发送换行符,并使用css样式white-space: pre,这将保留换行符,空格和制表符。

+0

好极了,这帮了我,避免了字符串替换码。 – Marcel 2013-12-05 10:35:11

2

我解决此得到了首先将数据从使用

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

然后我用雷Booysen的解决方案,使其返回到我的GridView多行文本框插入我的SQL Server表:

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 
2

Booysen的答案只适用于一列。如果你在RowDataBound事件中运行一个循环,你可以用一个变量代替[0],并且如果你愿意的话,可以在每一列上做这个工作。下面是我所做的:

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; 
     } 
    } 
} 

矿在1故意开始,因为我的数据,但显然它会与任何你需要的工作。

38

HtmlEncode property设置为false怎么样?对我来说,这更简单。

<asp:BoundField DataField="MyColumn" HtmlEncode="False" /> 
+4

同意。这很容易。 – willem 2011-03-18 12:32:25

3
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; 
     } 
    } 
} 
1
protected void gvHead_OnRowDataBound(object sender, GridViewRowEventArgs e) { 
    for (int i = 0; i < e.Row.Cells.Count; i++) 
    e.Row.Cells[i].Text = HttpUtility.HtmlDecode(e.Row.Cells[i].Text); 
} 
0

你要绑定到的DataBoundGrid事件并更改渲染你想渲染HTML代码列。

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; 
}; 
0

@Ray Booysen答案是正确的,但在某些情况下,HtmlDecode()无法处理您的问题。您可以使用UrlDecode()而不是HtmlDecode()。
这里是另一种解决方案:

if (e.Row.RowType == DataControlRowType.DataRow) 
{ 
    string decodedText = HttpUtility.UrlDecode(e.Row.Cells[0].Text); 
    e.Row.Cells[0].Text = decodedText; 
}