Infolink

 

Search This Blog

Nov 10, 2012

Create Html Table Dynamically

The following code dynamically creates a table with five rows and four cells per
row, sets their colors and text, and shows all this on the page. The interesting detail is that no control tags are declared in the .aspx file. Instead, everything is generated programmatically.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

public partial class DynamicTable : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        HtmlTable table1 = new HtmlTable();

        // Set the table's formatting-related properties.
        table1.Border = 1;
        table1.CellPadding = 0;
        table1.CellSpacing = 0;
        table1.BorderColor = "red";

        // Start adding content to the table.
        HtmlTableRow row;
        HtmlTableCell cell;
        for (int i = 1; i <= 3; i++)
        {
            // Create a new row and set its background color.
            row = new HtmlTableRow();
            row.BgColor = (i % 2 == 0 ? "lightgreen" : "lightgray");
            for (int j = 1; j <= 5; j++)
            {
                // Create a cell and set its text.
                cell = new HtmlTableCell();
                cell.InnerHtml = "Row: " + i.ToString() + "<br />Cell: " + j.ToString();
                // Add the cell to the current row.
                row.Cells.Add(cell);
            }

            // Add the row to the table.
            table1.Rows.Add(row);
        }

        // Add the table to the page.
        this.Controls.Add(table1);
    }
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...