Adding Rows and Cells Dynamically to a Table Control

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. Thus, you can add cells to a row by manipulating this collection.

   <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.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()));

   <div class="header">
           Generating Table Rows and Cells Dynamically</h3>
   <hr size="1" width="90%" />
   <div align="center">
       <form id="Form1" runat="server">
               <asp:Table ID="myTable" CellPadding="5" CellSpacing="0" GridLines="Both" runat="server" />
               Table rows
               <asp:DropDownList ID="rowsSelect" runat="server" />
               Table cells
               <asp:DropDownList ID="cellsSelect" runat="server" />
                   <asp:Button ID="Button1" Text="Generate Table" runat="server" />
   <hr size="1" width="90%" />
Next Post Previous Post
No Comment
Add Comment
comment url