German Wear Discount Shop - Click Here Write for Dotnet-friends and earn for your each submission [Dot]Net-Friends
Skip Navigation Links
Home
Latest
Fast Code
Articles
Tutorials
Online Resources
Forums
Login   | Hi, Guest


How to Create an HTML Table from a DataTable in ASP .NET

Written by omerkamal on Mar 30, 2007
Convert a DataTable to an HTML Table using ASP .NET and C#

Explanation:


We will make an account on creating an HTML Table from a DataTable. This can be very usefull in some cases when a small Data is need be displayed.

public static string ConvertToHtmlFile(DataTable sentDataTable)
{
 
    // Check if the Sent DataTable is not empty or a Null
    if (sentDataTable == null)
    {
        throw new System.ArgumentNullException("sentDataTable");
     }

 //Get a worker object.
 StringBuilder myStringBuilder = new StringBuilder();

 //Open tags and write the top portion.
 myStringBuilder.Append("");
 myStringBuilder.Append("");
 myStringBuilder.Append("");<br>  myStringBuilder.Append("Page-");<br>  myStringBuilder.Append(Guid.NewGuid().ToString());<br>  myStringBuilder.Append("");
 myStringBuilder.Append("");
 myStringBuilder.Append("");
 myStringBuilder.Append("

 myStringBuilder.Append("style='border: solid 1px Silver; font-size: x-small;'>");


 //Add the headings row.

 myStringBuilder.Append("

");

 foreach (DataColumn myColumn in sentDataTable.Columns)
 {
  myStringBuilder.Append("

");
 }

 myStringBuilder.Append("

");

 //Add the data rows.
 foreach (DataRow myRow in sentDataTable.Rows)
 {
  myStringBuilder.Append("

");

  foreach (DataColumn myColumn in sentDataTable.Columns)
  {
   myStringBuilder.Append("

");
  }

  myStringBuilder.Append("

");
 }

 //Close tags.
 myStringBuilder.Append("

");
  myStringBuilder.Append(myColumn.ColumnName);
  myStringBuilder.Append("
");
   myStringBuilder.Append(myRow[myColumn.ColumnName].ToString());
   myStringBuilder.Append("
");
 myStringBuilder.Append("");
 myStringBuilder.Append("");

    return myStringBuilder.ToString();
}

Visitors/Readers Comments
(for questions please use The Forum)



Guest

why not use datagrid or gridview?

03/04/2007 15:00:56 UTC

kamal

This was just an Idea. Of Course Gridview/Datagrid are dynamic implementaions of the Data Presentation and also there is no better replacement for that.

This also tells the way Gridview displays Data in the HTML Format.

03/04/2007 15:59:20 UTC

sibu abraham
How to add this script (html table) to html page in Asp Dot Net.

01/03/2008 06:02:19 UTC

Amit
Gridview is not suitable if i want to add values from javascript, or on client side

29/07/2008 22:25:01 UTC




Add your Comments

Name:  
Message:
Note: For faster response please use Forums >> for your questions instead of the comments area! (Admin)