How To Force Force x number of rows in a GridView Displaying Database Information Using a Table Control
Oct 06

It’s common to add rows and cells to a Table Web server control at run time. Rows are objects of type TableRow. The Row property of the Table control supports a collection of TableRow objects. To add a row to the table, you add a TableRow object to this collection.

Similarly, the TableRow object has a Cells property that supports a collection of objects of type TableCell. You can add cells to a row by manipulating this collection.


<html>
<head>
<title>Generating Table Rows and Cells Dynamically</title>

<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 ( ) );
      }
      rowsSelect.SelectedIndex = 1;
      cellsSelect.SelectedIndex = 2;
   }

   // generate rows and cells
   int numrows = int.Parse ( rowsSelect.SelectedItem.Value );
   int numcells = int.Parse ( cellsSelect.SelectedItem.Value );

   for ( int j = 0; j < numrows; j++ ) {
      TableRow r = new TableRow ( );
      for ( int i = 0; i < numcells; i++ ) {
         TableCell c = new TableCell ( );
         c.Controls.Add ( new LiteralControl ( "row " + j.ToString ( ) + ", cell " + i.ToString ( ) ) );
         r.Cells.Add ( c );
      }
      myTable.Rows.Add ( r );
   }
}
</script>
</head>

<body>

<div class="header"><h3>Generating Table Rows and Cells Dynamically</h3></div>

<hr size=1 width=90%>

<div align="center">
<form runat="server">

   <p><asp:table id="myTable" cellpadding=5 cellspacing=0 gridlines="Both" runat="server" /></p>

   <p>

   Table rows <asp:dropdownlist id="rowsSelect" runat="server" />

     

   Table cells <asp:dropdownlist id="cellsSelect" runat="server" />

   <p><asp:button text="Generate Table" runat="server" />

</form>
</div>

<hr size=1 width=90%>

</body>
</html>

Leave a Reply