2009-01-10 16 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; 
} 
相關問題