Wednesday, 12 February 2014

how to convert text of gridview cell into html in Dotnet

Description: While loading html content (html tags) from database or some other source Gridview converts that content into text and content is displayed as it is in browser.
We can convert html text content into html tags by using two ways.
A.  Using GridView Templates.
B.  Using HttpUtility.HtmlDecode functions of Asp.Net.

Using GridView templates:
1.    Define your template
 Eg. <asp:TemplateField> </asp:TemplateField>

2.    Define your ItemTemplate
 Eg. <asp:TemplateField> <ItemTemplate></ItemTemplate> </asp:TemplateField>

3.    Place your data inside itemTemplate
 Eg. <asp:TemplateField>
<ItemTemplate>
<%#Eval("URL").ToString()%> //Convert it into string
</ItemTemplate>
</asp:TemplateField>


Using HttpUtility.HtmlDecode
1)    Under row bound event , use HttpUtility.HtmlDecode to convert Text
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;
        }
    }
}

2)    After Databind() Event of GridView, loop through rows and cells to convert text in required Cell to Html tags.
/////////////////
//////////////////
            gvSearch.DataSource = dt;
            gvSearch.DataBind();
            for (int i = 0; i < gvSearch.Rows.Count; i++)
            {
             gvSearch.Rows[i].Cells[3].Text = HttpUtility.HtmlDecode(gvSearch.Rows[i].Cells[3].Text);
            }

No comments:

Post a Comment