Sunday, March 25, 2012

Converting Data Table to HTML Table and Displaying on the Aspx page

Author : Prakash Pradeep Gopu
Suppose If I have Table called Employee in my database if I Want to add this table dynamically to this my aspx page using C# code. This post will explain this.
To achieve this the following 3 steps you need to do:
1)    Retrieve the desired table you want to load dynamically in to data Table.
2)    Convert the data table in to Html Table
3)    Display it on the Aspx page.

Retrieve the desired table you want to load dynamically in to data Table.
The following code in the page Load even will able to connect to the database and will retrieve the data table from Database.

protected void Page_Load(object sender, EventArgs e)
        {
         
            //Reading the connection string from the Web.config file
            string connetion = ConfigurationManager.ConnectionStrings["Bloggerconnection"].ToString();
            //creating connetion object
            SqlConnection con = new SqlConnection(connetion);
            //DCreating data adapter object and connecting to database
            SqlDataAdapter da = new SqlDataAdapter("select * from [Practice].[dbo].[Tbl_Employee]", con);
            DataTable dt = new DataTable();
            //fill the Dataresult of data adpter in to the datatable
            da.Fill(dt);
            //Calling the CreateHtmlTable method (Step2)
            string str = CreateHtmlTableRows(dt, "Employee");
           //showing Html table on to the aspx page method (Step3)
            Literal1.Text = str;
        }


Convert the data table in to Html Table
The second step is using the Data table we are going to create a Html table.The following method will do this functionality:


public string CreateHtmlTableRows(DataTable targetTable, string strtblName)
        {
            StringBuilder myBuilder = new StringBuilder();
            if (strtblName != "")
                myBuilder.Append("<table Id='" + strtblName + "' border='2px' cellpadding='0' cellspacing='0' ");
            else
                myBuilder.Append("<table border='0px' cellpadding='0' cellspacing='0' ");
            myBuilder.Append("style='width: 100%;'>");
            //Add the headings row.
            myBuilder.Append("<tr align='left' valign='top' class='grdHeader'>"); //grdHeader class will be in CSS file

            foreach (DataColumn myColumn in targetTable.Columns)
            {
                myBuilder.Append("<td align='left' valign='top'>");
                myBuilder.Append(myColumn.ColumnName);
                myBuilder.Append("</td>");
            }
            myBuilder.Append("</tr>");
            //Add the data rows.
            int intI = 0;
            int totRow = targetTable.Rows.Count - 1;
            foreach (DataRow myRow in targetTable.Rows)
            {

                if (intI % 2 == 0)
                    myBuilder.Append("<tr align='left' class='grdOddRow'>");      //'grdOddRow'class will be in CSS file
                else
                    myBuilder.Append("<tr align='left' class='grdEvenRow'>"); //''grdEvenRow''class will be in CSS file

                foreach (DataColumn myColumn in targetTable.Columns)
                {
                    myBuilder.Append("<td align='left' valign='top'><b>");
                    myBuilder.Append(myRow[myColumn.ColumnName].ToString());
                    myBuilder.Append("</b></td>");
                }
                myBuilder.Append("</tr>");
                intI += 1;
            }
            //Close tags.
            return myBuilder.Append("</table>").ToString();
        }
 

Display it on the Aspx page.
 
The final step is show the html table on to the aspx page for this we need to create a literal control on the aspx page.The aspx page is will shown below:


<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">
    <title></title>
    <link href="Styles/StyleSheet1.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:Literal ID="Literal1" runat="server"></asp:Literal>
   
    </div>
    </form>
</body>
</html>
 

We need to assign the HTML string to the literal1 in the page load event.this can be done using the following single statement : Literal1.Text = str;
Where str is the string returned in the 2nd step.
Output :
 

3 comments:

  1. Thanks a lot for your sharing..This was what i exactly needed!!

    ReplyDelete
  2. The GridView control is able to convert datatable in GridView to HTML to viewing in a web browser.

    ReplyDelete
  3. Yea but GridView Sucks Ass when it come to dynamic data.

    ReplyDelete