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 id="Form1" 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 ID="Button1" Text="Generate Table" runat="server" /> </p> </form> </div> <hr size="1" width="90%" /> </body> </html>


No comments:
Post a Comment