How to show formatted html content in grid view?


In this article I have explained in detail how to show html formatted content in the grid view content. For example we are stored html content in the database show that content in grid view as like in web page output.

Description


Normally we are stored HTML contents in the SQL Server database during display that content in webpage grid that content is look like as a normal text instead of that using below code to show that content as formatted like coloring, bold etc.<br/>

Client side:
I have placed one grid view control in the web page like below

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None" onrowdatabound="GridView1_RowDataBound">
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<RowStyle Height="100" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
</div>
</form>
</body>
</html>

Server side


I have created one data table and assign one html content data row in that data table and bind in the grid view

using System.Data;

public partial class _Default : System.Web.UI.Page
{
DataTable dt = new DataTable();
DataRow dr;

protected void Page_Load(object sender, EventArgs e)
{
//create one column in datatable
dt.Columns.Add("Html Content");
//create new row in the datatable
dr = dt.NewRow();
//add some html content in the datatable using datarow
dr["Html Content"] = "<b>Html Content Display in Gridview </bGT;. <br/GT;<font color='red'GT;This is HTML content and formatted in the gridveiw cell</fontGT;";
dt.Rows.Add(dr);
//Bind data into gridview
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Using below loop i have formatted that html content and show as like in web page
foreach (TableCell cell in e.Row.Cells)
{
cell.Text = Server.HtmlDecode(cell.Text);
}
}
}

Output
Output

Conclusion:
I hope this article help you to know about how to handled html contents inside of grid view control.


Comments

Guest Author: vcartera24 Jun 2013

Doesn't work for me. it stills shows tags in text instead of format them