How to Convert GridView Data in to Html Table

Self-Innovator
Posted by in ASP.NET category on for Beginner level | Points: 250 | Views : 16812 red flag

This article explains on how the Grid View data can be converted to HTML Table.

Introduction


In this article we are going to see how to convert the grid view data to HTML table. In many web applications the users may tend to an requirement of changing the grid view data to html table.

Objective


Grid View Control is commonly used in most of the web applications in order to perform many operations like edit,view,update etc. The users may come in some requirement to change the content of a grid view data into HTML table.


Using the code


Two tables tbl_PersonalDetails and tbl_ContactDetails are used in this article for displaying the content on grid view based on users selection.

Screen 1




Screen 2




The below code is an page design which consists of Check box list controls with Personal Details and Contact Details as an users option
.aspx Page Design


<table align="center">
<tr>
<td align="center"><b>
Grid View to Html Conversion
</b></td>
</tr>
<tr>
<td>
<asp:CheckBoxList ID="chkContactDetails" runat="server"
RepeatDirection="Horizontal" AutoPostBack="True"
onselectedindexchanged="chkContactDetails_SelectedIndexChanged">
<asp:ListItem>Contact Details</asp:ListItem>
<asp:ListItem>Personal Details</asp:ListItem>
</asp:CheckBoxList>
</td>
</tr>
</table>
The below code is an page design which consists of two grid view controls which will display the  Personal Details and Contact Details as an users according to users selection.
.aspx Page Design


<table align="center">
<tr>
<td>
<asp:GridView ID="grdCntDetails" runat="server" AutoGenerateColumns="False"
Width="400px" BackColor="#FFAA2B">
<Columns>
<asp:BoundField HeaderStyle-HorizontalAlign="Left" HeaderText="Name"
DataField="Name" >
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
</asp:BoundField>
<asp:BoundField HeaderStyle-HorizontalAlign="Left" HeaderText="Mobile"
DataField="Mobile" >
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
</asp:BoundField>
</Columns>
<EditRowStyle BackColor="#FFE8C4" />
</asp:GridView>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="grdPersDetails" runat="server" AutoGenerateColumns="False"
Width="400px" BackColor="#FFAA2B">
<Columns>
<asp:BoundField HeaderStyle-HorizontalAlign="Left" HeaderText="Name"
DataField="Name" >
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
</asp:BoundField>
<asp:BoundField HeaderStyle-HorizontalAlign="Left" HeaderText="Email"
DataField="Email" >
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
</asp:BoundField>
</Columns>
<EditRowStyle BackColor="#FFE8C4" />
</asp:GridView>
</td>
</tr>
<tr>
<td align="center">
<asp:Button ID="btnConvert" runat="server" Text="Grid to Html"
onclick="btnConvert_Click" />
</td>
</tr>
</table>
The designing of the page is done here the rest of the code will consist of .cs files as an users option
Code Behind .cs

Below are the list of namespaces required to generate Grid view content to an HTML


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using System.IO;
Db Connection-Connection string

The below line determines the connection string to database using MS-SQL Server 2005
 string Conn = ConfigurationManager.ConnectionStrings["MyDBConnection"].ConnectionString;
Global Variables

Some global variables are declared to maintain the data under those variables globally
 DataSet ds = new DataSet();
string Body;
Check Box List Selected Changed Event

The below event is looping through the n number of items and and displaying the specific details of the users according to calling it's associated function. In the example 2 items (Contact Details,Personal Details) are used.
 protected void chkContactDetails_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < chkContactDetails.Items.Count; i++)
{
if (chkContactDetails.Items[i].Selected == true)
{
if (chkContactDetails.Items[i].Text == "Contact Details")
{
CntDetailsToHtml();
}
else if (chkContactDetails.Items[i].Text == "Personal Details")
{
PersDetailsToHtml();
}
}
else if (chkContactDetails.Items[i].Selected == false)
{
if (chkContactDetails.Items[i].Text == "Contact Details")
{
grdCntDetails.Visible = false;
}
else if (chkContactDetails.Items[i].Text == "Personal Details")
{
grdPersDetails.Visible = false;
}
}
}
}
User Defined Methods

Method explained below binds the contact details of the user to contact grid view and for personal details.
 protected DataSet CntDetailsToHtml()
{
try
{
SqlConnection cnn = new SqlConnection(Conn);
SqlCommand cmd = new SqlCommand("select * from tbl_ConactDetails", cnn);
SqlDataAdapter ada = new SqlDataAdapter(cmd);
ada.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
grdCntDetails.Visible = true;
grdCntDetails.DataSource = ds;
grdCntDetails.DataBind();
}
else
{
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
return ds;
}


protected DataSet PersDetailsToHtml()
{
try
{
SqlConnection cnn = new SqlConnection(Conn);
SqlCommand cmd = new SqlCommand("select * from tbl_PersonalDetails", cnn);
SqlDataAdapter ada = new SqlDataAdapter(cmd);
if (ds != null)
{
ds = new DataSet();
}
ada.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
grdPersDetails.Visible = true;
grdPersDetails.DataSource = ds;
grdPersDetails.DataBind();
}
else
{
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
return ds;
}
On Button Click Event

The button click event will just convert the content Grid View data in to an HTML table by calling it's associated method to convert in to HTML table


protected void btnConvert_Click(object sender, EventArgs e)
{
if (chkContactDetails.SelectedIndex <= -1)
{
ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert('Please select any of the contact details');", true);
}
else
{
string B = fn_AttachGridView();
Response.Write(B.ToString());
}

}
On Button Click Event

The button click event will just convert the content Grid View data in to an HTML table by calling it's associated method to convert in to HTML table. It first checks for any of the contact Details has been selected to convert.


protected void btnConvert_Click(object sender, EventArgs e)
{
if (chkContactDetails.SelectedIndex <= -1)
{
ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert('Please select any of the contact details');", true);
}
else
{
string B = fn_AttachGridView();
Response.Write(B.ToString());
}

}
User Defined Method

The button click event uses an fn_AttachGridView() an user defined function which in then calls the other function (ContatDtlsToHtml , PersonalDtlsToHtml)to convert it to HTML table.


protected string ContatDtlsToHtml(GridView grdC)
{
ds = CntDetailsToHtml();
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(sw);
if (ds.Tables[0].Rows.Count > 0)
{
sb.AppendLine("<html><body><center><table width='50%' cellspacing='0' border='1'");
sb.AppendLine("<tr>");
sb.AppendLine("<td colspan='4' width='50%' align='center' style='background-color: #FFAA2B;'>");
sb.AppendLine("<b>");
sb.AppendLine("Contact Details");
sb.AppendLine("</b>");
sb.AppendLine("</td>");
sb.AppendLine("</tr>");
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
sb.AppendLine("<tr style='background-color: #FFE8C4'>");
sb.AppendLine("<td>");
sb.AppendLine("<b>");
sb.AppendLine("Name");
sb.AppendLine("</b>");
sb.AppendLine("</td>");
sb.AppendLine("<td>");
sb.AppendLine(ds.Tables[0].Rows[i]["Name"].ToString().ToUpper());
sb.AppendLine("</td>");
sb.AppendLine("<td>");
sb.AppendLine("<b>");
sb.AppendLine("Mobile");
sb.AppendLine("</b>");
sb.AppendLine("</td>");
sb.AppendLine("<td>");
sb.AppendLine(ds.Tables[0].Rows[i]["Mobile"].ToString().ToUpper());
sb.AppendLine("</td>");
sb.AppendLine("</tr>");
}
sb.AppendLine("</table></center></body></html>");
}
return sb.ToString();
}

protected string PersonalDtlsToHtml(GridView grdP)
{
ds = null;
ds = new DataSet();
ds = PersDetailsToHtml();
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(sw);
if (ds.Tables[0].Rows.Count > 0)
{
sb.AppendLine("<html><body><center><table width='50%' cellspacing='0' border='1'");
sb.AppendLine("<tr>");
sb.AppendLine("<td colspan='4' width='50%' align='center' style='background-color: #FFAA2B;'>");
sb.AppendLine("<b>");
sb.AppendLine("Personal Details");
sb.AppendLine("</b>");
sb.AppendLine("</td>");
sb.AppendLine("</tr>");
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
sb.AppendLine("<tr style='background-color: #FFE8C4'>");
sb.AppendLine("<td>");
sb.AppendLine("<b>");
sb.AppendLine("Name");
sb.AppendLine("</b>");
sb.AppendLine("</td> ");
sb.AppendLine("<td>");
sb.AppendLine(ds.Tables[0].Rows[i]["Name"].ToString().ToUpper());
sb.AppendLine("</td>");
sb.AppendLine("<td>");
sb.AppendLine("<b>");
sb.AppendLine("Email");
sb.AppendLine("</b>");
sb.AppendLine("</td> ");
sb.AppendLine("<td>");
sb.AppendLine(ds.Tables[0].Rows[i]["Email"].ToString());
sb.AppendLine("</td>");
sb.AppendLine("</tr>");
}
sb.AppendLine("</table></center></body></html>");
}
return sb.ToString();
}
Screen 1

Screen 2


Conclusion

The above article can be used in any of the web application where there is a need for converting grid view to HTML table.




Page copy protected against web site content infringement by Copyscape

About the Author

Self-Innovator
Full Name: Sayeed Ahmed
Member Level: Bronze
Member Status: Member
Member Since: 12/22/2011 7:45:35 AM
Country: India
Join Hands Change lives Thanks & Regards Straight Edge Society


Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)