<html>
<head>
<title>Generating HtmlTable Rows and Cells Dynamically</title>
<link rel="stylesheet" href="/shared/netdemos.css">
<script language="C#" runat="server">
void Page_Load ( object src, EventArgs e ) {
if ( !IsPostBack ) {
// generate select options
for ( int i = 1; i <= 5; i++ ) {
rowsSelect.Items.Add ( i.ToString ( ) );
cellsSelect.Items.Add ( i.ToString ( ) );
}
}
// get the number of rows and cells to build
int numrows = Convert.ToInt32 ( rowsSelect.Value );
int numcells = Convert.ToInt32 ( cellsSelect.Value );
// loop through the given number of rows
for ( int r = 0; r < numrows; r++ ) {
// instantiate a new row
HtmlTableRow row = new HtmlTableRow ( );
// set bgcolor for alternating rows
if ( r % 2 == 1 ) row.BgColor = "beige";
// loop through the given number of cells
for ( int c = 0; c < numcells; c++ ) {
// instantiate a new cell
HtmlTableCell cell = new HtmlTableCell ( );
// add cell content
cell.Controls.Add ( new LiteralControl ( "row " + r.ToString ( ) +
", cell " + c.ToString ( ) ) );
// add the cell to the Cells collection
row.Cells.Add ( cell );
}
// add the row to the Rows collection
myTable.Rows.Add ( row );
}
}
</script>
</head>
<body>
<!-- #include virtual="~/shared/top.inc -->
<div class="header"><h2>Generating <span class="hilite">HtmlTable</span> Rows and Cells Dynamically</h2></div>
<hr size=1 width=92%>
<center>
<form runat="server">
<table id="myTable" cellpadding=3 border=1 runat="server" />
<p>
Table rows <select id="rowsSelect" runat="server" />
Table cells <select id="cellsSelect" runat="server" />
</p>
<p><input type=submit value="Show me" runat="server"></p>
</form>
</center>
<hr size=1 width=92%>
<!-- #include virtual="~/shared/viewsrc.inc" -->
</body>
</html>