Creating HTMLTable Dynamically

          The blog is intended to demonstrate the use of some HTMLControls for dynamically generating the HTMLTable on webpage using some piece of code.
          Required Namespace: System.Web.UI.HtmlControls
Controls used:
1.    Two Textboxes (txtRow & txtCol)
2.    One Button (btnClick)
3.    One Blank Table (htmlTable1)
Step 1: Accept the no. of Rows and Columns from User.
            int row = Convert.ToInt32(txtrow.Text);     // No. of Rows
            int col = Convert.ToInt32(txtcol.Text);     // No. of Columns
 Listing 1
Step 2: Now, Initialize the new TableRow & TableCell to add Data into Table.
            for (int i = 0; i < row; i++)
                  HtmlTableRow rows = new HtmlTableRow();         //a new Row
                  for (int j = 0; j < col; j++)
                        HtmlTableCell cell = new HtmlTableCell(); //a new Cell
Listing 2
Step 3: You can put any data into Cell, also can make some FORMATTING for good looks, and then add this cell to the row element…
                   cell.InnerHtml = i + “,” + j;               //Insert Data into Cell
            cell.Align = “Center”;
            cell.BorderColor = “Gray”;
            rows.Cells.Add(cell);                       //Attach Cell with Row
Listing 3
Step 4: Now, simply insert this row element into htmlTable1 to display that row on the screen.
               htmlTable1.Rows.Add(rows);                      //Attach Row with Table
Listing 4
Step 5: Now execute the web application and see the result.
Intended Result:

Figure 1
          In this piece of writing, we see how to generate the HTML table with user accepted rows and columns. For writing the code here I used the C# and ASP.NET.
Mayur Dighe

Leave a Reply

Your email address will not be published. Required fields are marked *