Html Encode values for Telerik’s RadGrid control

Posted by Max | Posted in .net | Posted on 25-01-2008

3

RadGrid GridBoundColumn values are not HTML encoded by default (see screenshot), so there is a risk of cross site scripting attack.

RadGrid control and MS GridView controls displaying string array

Extract from code behind:

protected void Page_Load(object sender, EventArgs e)
{
    string[] str = new string[] {
        "test

string

" }; radGrid.DataSource = str; radGrid.DataBind(); GridView1.DataSource = str; GridView1.DataBind(); }

There is no Html encode option available at this moment so the best you can do is to encode values with ItemDataBound event:

protected void RadGrid1_ItemDataBound(object sender, Telerik.WebControls.GridItemEventArgs e)
{
    if (e.Item is GridDataItem)
    {
        GridDataItem item = e.Item as GridDataItem;
        item["Content"].Text = Server.HtmlEncode(item["Content"].Text);
    }
}

More information about this on Telerik support forum.

Another option is to create new new class which inherits from RadGrid column (e.g. GridBoundColumn) and override its PrepareCell method:

ASPX page:


    
        
            
        
    

Code behind:

public class MyGridBoundColumn : Telerik.WebControls.GridBoundColumn
    {
        private bool _htmlEncode = true;

        public bool HtmlEncode
        {
            get { return _htmlEncode; }
            set { _htmlEncode = value; }
        }

        public override void PrepareCell(
            TableCell cell,
            Telerik.WebControls.GridItem item
        )
        {
            base.PrepareCell(cell, item);
            if (_htmlEncode)
            {
                cell.Text = HttpUtility.HtmlEncode(
                    cell.Text
                );
            }
        }
    }

Comments (3)

Увлекательно написано. А вообще, поздравляю автора сайта и всех его читателей с сегодняшним праздником – Днем России. Ура, товарищи! :)

Hi great stuff. As an alternative you can use this:

namespace RadGrid.Extenders
{
using System.Web;
using Telerik.WebControls;

public class HtmlEncodedGridHyperLinkColumn : GridHyperLinkColumn
{
protected override string FormatDataTextValue(object dataTextValue)
{
return HttpUtility.HtmlEncode((base.FormatDataTextValue(dataTextValue)));
}
}
}

As of 2008 Q2, GridBoundColumn now has a HtmlEncode property.

Write a comment