Thursday 1 November 2012

Convert DataTable to HTML


Convert DataTable to HTML


We come across situations when we want to get the HTML of the Datatable to display it on the page or send it in an email.. So here is the code snippet to achieve this:


    DataTable dtPriceDetails = SOME DATA TABLE  

     

    if (dt.Rows.Count > 0) 

    { 

    string StringDataTable = ConvertToHtmlFile(dtPriceDetails); 

    } 

     

      public static string ConvertToHtmlFile(DataTable targetTable) 

      { 

        string myHtmlFile = ""; 

     

    if (targetTable == null) 

          { 

            throw new System.ArgumentNullException("targetTable"); 

    } 

          else 

          { 

            //Continue.  

    } 

     

    //Get a worker object. 

          StringBuilder myBuilder = new StringBuilder(); 

     

          //Open tags and write the top portion.  

          //myBuilder.Append(""); 

          //myBuilder.Append(""); 

          //myBuilder.Append(""); 

          //myBuilder.Append(""); 

          //myBuilder.Append(""); 

          myBuilder.Append("); 

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

     

    //Add the headings row. 

          myBuilder.Append(""); 

    foreach (DataColumn myColumn in targetTable.Columns) 

          { 

            myBuilder.Append(""); 

          myBuilder.Append(myColumn.ColumnName); 

            myBuilder.Append(""); 

          } 

          myBuilder.Append(""); 

     

    //Add the data rows.  

          foreach (DataRow myRow in targetTable.Rows) 

          { 

            myBuilder.Append(""); 

     

    foreach (DataColumn myColumn in targetTable.Columns) 

                { 

                    myBuilder.Append(""); 

                      myBuilder.Append(myRow[myColumn.ColumnName].ToString()); 

                      myBuilder.Append(""); 

    } 

     

                myBuilder.Append(""); 

    } 

     

          //Close tags.  

          myBuilder.Append(""); 

          //myBuilder.Append("");  

          //myBuilder.Append(""); 

     

          //Get the string for return.  

          myHtmlFile = myBuilder.ToString(); 

     

          return myHtmlFile; 

    }  


No comments:

Post a Comment

Thank You for Your Comments. We will get back to you soon.

back to top