ASP.Net 2.0 provides HtmlControls namespace having number of classes that allow you generate different types of Html controls dynamically. You can generate dynamic tables, Ordered Lists, Unordered Lists, html buttons and much more. In classic asp there was very common use of loops to generate dynamic html tables using string variable and concatenating its value each time code is executed between the loop block. In ASP.Net 2.0 Microsoft has introduced most of Html controls under the HtmlControls namespace.
Here we will learn the use of HtmlTable class along with HtmlTableRow and HtmlTableCell classes to generate the dynamic Html table using C# code.
HtmlTable class: This class allows the access on the server to generate HTML <table> element.
HtmlTableRow class: This class represents the <tr> tag for html table that creates a space to add new row in table.
HtmlTableCell class: This class represents the <td> or <th> tag of Html table that creates a cell in table row.
You can use the Panel server control to add the dynamically created instance of HtmlTable to generate the table on web page.
HtmlTable dTable = new HtmlTable(); dTable.CellPadding = 2; dTable.CellSpacing = 0; dTable.Border = 1; dTable.BorderColor = "#cccccc";
int tRows; int tCells;
for (tRows = 0; tRows < 5; tRows++) { HtmlTableRow dTRow = new HtmlTableRow(); for (tCells = 0; tCells < 4; tCells++) { HtmlTableCell dTCell = new HtmlTableCell(); dTCell.InnerText = "Row:: " + Convert.ToString(tRows + 1) + " Col:: " + Convert.ToString(tCells + 1); dTRow.Controls.Add(dTCell); } dTable.Controls.Add(dTRow); }
Panel1.Controls.Add(dTable);
Note that after creating a new instance for any class e.g. dTable for HtmlTable, you can access all the html type attributes or properties of <table> element, like cellpadding, cellspacing in above example.
Be the first to rate this post
Tags: asp.net 2.0, dynamic table, c# code, htmlcontrols, htmltable, htmltablerow, htmltablecell, free source code, panel control
7/24/2008 5:26:05 PM