Template column and HTML Encoding

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.HtmlDecode(Eval("ColumnName").ToString()) %>'></asp:Label>

Vikram


Share this post   Email it |  digg it! |  reddit! |  bookmark it!

Feedback

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 
Copyright © 2006 - 2009 Vikram Lakhotia