Friday, 4 January 2013

How to create Table Dynamically in asp.net with C#

Write the following code in your code behind page(.aspx.cs) 

using System.Web.UI.HtmlControls;

protected void Page_Load(object sender, System.EventArgs e)
        {
            // Create a new HtmlTable object.
            HtmlTable table1 = new HtmlTable();

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

            // Start adding content to the table.
            HtmlTableRow row;
            HtmlTableCell cell;
            for (int i = 1; i <= 2; i++)
            {
                // Create a new row and set its background color.
                row = new HtmlTableRow();
                row.BgColor = "lightyellow";
                for (int j = 1; j <= 3; 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);
        }

For any other queries feel free to post a comment.

No comments:

Post a Comment