HTML Encoding a label inside a Template column
Hi,
I have seen this question a few times in the forum so decided to blog on that. Many a times we store HTML characters in the database. When we want to show these values in the Gridview, detailsview or similar control.
But when we are displaying the value we want to encode (or sometime even decode) the value displayed. With bound column we get a property to HTMLEncode the value, but what do we do when we are using template column.
When we are using template Column we have two ways to HTML Encode (or decode the data). Firstly we can do the encoding in code in the rowdatabaound event
protected void myGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label l = (Label)e.Row.FindControl(“ControlName”);
l.Text = HttpUtility.HtmlEncode(l.Text); //We can also use HtmlDecode if we want to decode the string
}
}
We can also do it in the aspx itself while binding the control
<asp:Label ID="Label1" runat="server" Text='<%# Server.HtmlEncode(Eval("ColumnName").ToString()) %>'></asp:Label>
Vikram