Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

This is a project I am working on, which generates an HTML table out of a query result.

(The result DataTable of an SQL command via SP)

This section of the project is the one that will generate the headers of the table according to the list of columns of each table selected (from the database list of tables). What I am trying to review here is the section that's responsible for generating an HTML markup programmatically.

I would like to know your opinion and what you would do differently.

In aspx, I will move this back after tests are completed:

   //instantiating class to Get A List<string> returned (of all db table-columns)
  // this code is  inplementing  GetClassFields class
  // you can see its code in section #2 below (helpers section)

    var TableColscls = GetClassFields.AsListStr(GetClassFields.SelectedClass.tables, tbls.TblTimeCPAReport);


Then using the list above for the generated HTML table:

<div style="width:90%; " dir="rtl">



.cs code behind

 // some usings 
 using Lsts = HTMLGenerator.dataSource.List;

 // this is what i call HTML TABLE GENERATOR 
 // or DB TO HTML Tables Adapter

public string RenderHtmlTblHeaders(List<string> SelectedListStr)

    List<string> OmittedCols = new List<string>();

    StringBuilder NwTRLoopSB = new StringBuilder();

    string curRowStyle= string.Empty,
           nwLine = Environment.NewLine + "\t\t\t",
           BaseTemplateTD = string.Empty;

                "<table id='tbl_Settings' cellspacing='0' border='1'><tr id='TR_headers'{0}>{1}",

//a new approach i've discovered (in one of the posts on `SO` )
//to have a counter with foreach loops

    foreach (var Item in SelectedListStr.Select((Val, counter) => new { Value = Val, Index = counter }))

            if(Lsts.ExcludeColumns(Item.Value, OmittedCols))
                BaseTemplateTD = string.Format("<td>{0}</td>{1}", Item.Value, nwLine)._Dhtml_DoubleQoutes();

    }///ENd TR cells generator Section

    return NwTRLoopSB.ToString();

.cs helper namespaces and classes

The code blocks below are extracted by relevance to this project as it (the whole file) serves all of my projects as a bunch of helpers.


This one is used to avoid the use of \" within formatted text:

                /// <summary>
                /// Replaces a single Quote with Double. used for html Attributes:
                /// </summary>
                public static string _Dhtml_DoubleQoutes(this string NewTRString)
                    return NewTRString.Replace("'", "\"");

class to list

    // using reflection to list / extract all fields of a given class

    public  class GetClassFields
        public enum SelectedClass
            tables, columns, ColHeaders

        public List<string> AsListStr(SelectedClass tabls_Cols_StoerdProc, string TableName)

            var tbls = new HTDB_Tables();
            HTDB_Cols Cols = new HTDB_Cols();
            var ColHeds = new Htdb_PresentedHebColHeaders();

            switch (tabls_Cols_StoerdProc)
                case SelectedClass.tables:
                    return typeof(HTDB_Tables).GetFields()
                     .Select(f =>f.GetValue(tbls).ToString()).ToList<string>();

                case SelectedClass.columns:
                    return typeof(HTDB_Cols).GetNestedTypes()
                    .First(t => String.Compare(t.Name, TableName, true) == 0)
                    .Select(f => f.GetValue(Cols).ToString())
                case SelectedClass.ColHeaders:

                    return typeof(Htdb_PresentedHebColHeaders).GetNestedTypes()
                        .First(t => String.Compare(t.Name, TableName, true) == 0)
                        .Select(f => f.GetValue(ColHeds).ToString())

                    return typeof(HTSPs.GetWorkerNameAndDataForTcReportCPABySnif_Fields).GetNestedTypes()
                    .First(t => String.Compare(t.Name, TableName, true) == 0)
                    .Select(f => f.GetValue(null) as string)



HTML Generator

(This is the short version; you could see my other post for a longer version)

Another method to produce style-background-color as bgColor of the alternation of rows within the HTML generated table:

public class HTMLGenerator
   //i guess i will add whats in cs code behind to this next section of helpers

            public class HTMFactory

                public static string DynamicStyle_Generator
                    int RowCounter = -1,
                    Dictionary<string, string> StyleAttributeDict = null
                    string BaseStyle = "", propTerminator = "'", BgCol = "";

                    StringBuilder StylerSB = new StringBuilder();

                    BgCol = "";
                    bool bgclaltrnator;
                    if (RowCounter >= 0)
                        bgclaltrnator = (RowCounter % 2) == 0;
                        if (bgclaltrnator)
                            BgCol = "#70878F";
                        else BgCol = "#E6E6B8";
                    BaseStyle = string.Format("style='background-color:{0};", BgCol);

                    ///string.Format("{0}:{1};", StlProps.BgColor, val);
                    return string.Concat(BaseStyle, StyleAttributeDict, propTerminator);


   // when inside the loop this will supply the correct "data source"
   // that will be the content of the table cells
   // for now it is the "selector" of which column to omitt method that 
   // i have placed here...

    public class dataSource
        public sealed class List

            public static bool ExcludeColumns
                                            string ListItem,
                                            List<string> OmittedColumns
                    bool Ret = false;

                        foreach (string col in OmittedColumns)
                            Ret = string.Compare(ListItem, col) ==0;
                            if (Ret)
                                return false;

                        return true;

share|improve this question
Have you looked using the HTML Agility Pack. It may be overkill but it might also make some of the steps easier. – Gene S Dec 17 '12 at 22:51
@GeneS I know HtmlAgilityPack... I am using it for parsing html documents , what else , I couldn't connect the idea ...(4am here) of usage with HtmlAgilityPack , as i don't really know more of it's features, but those I've already used for Parsing , so which part are you referring to and what features of HtmlAgilityPack would cover for it better ? , thanks for your time. – LoneXcoder Dec 18 '12 at 2:48
You can also use it to create new Html documents. I'm not an expert with it so I am not sure if it would end up being too tedious to create new elements. But if not, it might be a nice way to create the document in an object-oriented fashion. – Gene S Dec 18 '12 at 15:53
@GeneS thanks mate . i will look in to this aspect of the HtmlAgilityPack as i like to discover new implementation and see if it is more appropriate or easy to manipulate . did you ever try to pool some tricks of not having to hardcode your markup, also because it will be required as it will unnecessarily repeat itself – LoneXcoder Dec 18 '12 at 16:06
No sorry, I have not had to do this. I suspect if you find the HtmlAgilityPack an acceptable solution you will have less hardcoded markup because you will be creating elements instead of strings. – Gene S Dec 18 '12 at 17:31

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.