Mega Code Archive

 
Categories / ASP.Net Tutorial / HTML Controls
 

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);       }     }   } }