public class CustomeGrid
{
private string Table;
private StringBuilder TableRow;
private StringBuilder DataColumn;
private List<CustomeGridColumn> GridColumns;
private DataTable dataTable;
public CustomeGrid(DataTable dt)
{
dataTable = dt;
}
private void CreteTableHeader()
{
Table = "<table>";
int index = 0;
GridColumns = new List<CustomeGridColumn>();
foreach (DataColumn col in dataTable.Columns)
{
Table += "<th>" + col.ColumnName + "</th>";
GridColumns.Add(new CustomeGridColumn { Index = index, Name = col.ColumnName });
index++;
}
}
private void CreateRow()
{
TableRow = new StringBuilder();
TableRow.Append("<tr>");
}
private void CloseRow()
{
TableRow.Append("</tr>");
Table += TableRow.ToString();
}
private void CreateColumn(CustomeGridColumn col)
{
SetRowSpan(col);
DataColumn = new StringBuilder();
DataColumn.Append("<td #'"+col.Name+"'#>");
DataColumn.Append("<span>");
}
private void CloseColumn()
{
DataColumn.Append("</span>");
DataColumn.Append("</td>");
TableRow.Append(DataColumn.ToString());
}
private void AddData(string data)
{
DataColumn.Append(data);
}
private void CloseTable()
{
Table += "</table>";
SetRowSpanOnEndOfDataTable();
}
private void SetRowSpan(CustomeGridColumn col)
{
Table = Table.Replace("#'" + col.Name + "'#", "rowspan='" + col.RowSpan + "'");
}
private void SetRowSpanOnEndOfDataTable()
{
GridColumns.ForEach(delegate(CustomeGridColumn gc)
{
SetRowSpan(gc);
});
}
public string GetHtmlGrid()
{
CreteTableHeader();
foreach (DataRow row in dataTable.Rows)
{
CreateRow();
GridColumns.ForEach(delegate(CustomeGridColumn gc)
{
if (gc.PreviousValue != row[gc.Name].ToString())
{
CreateColumn(gc);
gc.RowSpan = 1;
gc.PreviousValue = row[gc.Name].ToString();
AddData(row[gc.Name].ToString());
CloseColumn();
}
else
gc.RowSpan++;
});
CloseRow();
}
CloseTable();
return Table;
}
}
public class CustomeGridColumn
{
public int Index { get; set; }
public string Name { get; set; }
public string PreviousValue { get; set; }
public int RowSpan { get; set; }
}
<
initialize the CustomeGrid class with the ordered data table from SQL query
and call the GetHtmlGrid() method in CustomeGrid class and it will =return a html string with the formated html table like the code lines below
CustomeGrid grid = new CustomeGrid(orderedDataTable);
TableContainer.InnerHtml = grid.GetHtmlGrid();