# DataTable 'adapter' to HTML table generator

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">

</div>


.cs code behind

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

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

{

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

StringBuilder NwTRLoopSB = new StringBuilder();

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

NwTRLoopSB.Append(
string.Format(
curRowStyle,
nwLine
)._Dhtml_DoubleQoutes()
);

//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();
NwTRLoopSB.Append(BaseTemplateTD);
}

}///ENd TR cells generator Section

NwTRLoopSB.Append("</tr></table>");
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.

Extensions

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
{
}

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

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

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)
.GetFields()
.Select(f => f.GetValue(Cols).ToString())
.ToList<string>();

.First(t => String.Compare(t.Name, TableName, true) == 0)
.GetFields()
.Select(f => f.GetValue(ColHeds).ToString())
.ToList<string>();

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

}
}

}


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
{

//TablesAlternatingRow
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)
{
RowCounter++;
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;
}

}
}
}

-
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