Dynamically create a HTML table (C#) : Table « HTML Controls « ASP.NET Tutorial

Home
ASP.NET Tutorial
1.ASP.Net Instroduction
2.Language Basics
3.ASP.net Controls
4.HTML Controls
5.Page Lifecycle
6.Response
7.Collections
8.Validation
9.Development
10.File Directory
11.Sessions
12.Cookie
13.Cache
14.Custom Controls
15.Profile
16.Configuration
17.LINQ
18.ADO.net Database
19.Data Binding
20.Ajax
21.Authentication Authorization
22.I18N
23.Mobile
24.WebPart
25.XML
ASP.NET Tutorial » HTML Controls » Table 
4.14.1.Dynamically create a HTML table (C#)
File:

<%@ Page language="c#" Inherits="TablePictures" CodeFile="Default.aspx.cs" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>Table Test</title>
</head>
<body>
  <form runat="server">
  <div>
    Rows:
    <asp:TextBox ID="txtRows" runat="server" />&nbsp;
    Cols:
    <asp:TextBox ID="txtCols" runat="server" />
    <br /><br />
    <asp:CheckBox ID="chkBorder" runat="server"
         Text="Put Border Around Cells" />
    <br /><br />
    <asp:Button ID="cmdCreate" OnClick="cmdCreate_Click" runat="server"
     Text="Create" />
    <br /><br />
    <asp:Table ID="tbl" runat="server" />
  </div>
  </form>
</body>
</html>



File: Default.aspx.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

public partial class TablePictures : System.Web.UI.Page
{
  protected void Page_Load(object sender, System.EventArgs e)
  {
    tbl.BorderStyle = BorderStyle.Inset;
    tbl.BorderWidth = Unit.Pixel(1);
  }

  protected void cmdCreate_Click(object sender, System.EventArgs e)
  {
    tbl.Controls.Clear();

    int rows = Int32.Parse(txtRows.Text);
    int cols = Int32.Parse(txtCols.Text);
    
    for (int i = 0; i < rows; i++)
    {
      TableRow rowNew = new TableRow();
      tbl.Controls.Add(rowNew);
      for (int j = 0; j < cols; j++)
      {
        TableCell cellNew = new TableCell();
        Label lblNew = new Label();
        lblNew.Text = "(" + i.ToString() "," + j.ToString() ")<br />";

        System.Web.UI.WebControls.Image imgNew = new System.Web.UI.WebControls.Image();
        imgNew.ImageUrl = "cellpic.png";

        cellNew.Controls.Add(lblNew);
        cellNew.Controls.Add(imgNew);

        if (chkBorder.Checked == true)
        {
          cellNew.BorderStyle = BorderStyle.Inset;
            cellNew.BorderWidth = Unit.Pixel(1);
          }

        rowNew.Controls.Add(cellNew);
      }
    }
  }
}
4.14.Table
4.14.1.Dynamically create a HTML table (C#)
4.14.2.Dynamic html table
4.14.3.InnerHtml
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.