SIGN UP MEMBER LOGIN:    
ARTICLE

Creating a table programmatically in ASP.NET

Posted by Puran Mehra Articles | ASP.NET Controls in C# February 04, 2010
In this article I will explain creating a table programmatically in ASP.NET.
Reader Level:

This article has been excerpted from book "A Programmer's Guide to ADO.NET in C#".

You can even create a table and add its cells and cell values programmatically. First, create a table using the <asp:Table> tag and then add rows to it(see Listing 7-27).

Listing 7-27. Creating a table's rows programmatically 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Creatingtableprogrammatically._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Table ID="table1" runat="server" Height="114" Width="439" BackColor=Aqua>
            <asp:TableRow>
            </asp:TableRow>
            <asp:TableRow>
            </asp:TableRow>
            <asp:TableRow>
            </asp:TableRow>
            <asp:TableRow>
            </asp:TableRow>
            <asp:TableRow>
            </asp:TableRow>
        </asp:Table>
    </div>
    </form>
</body>
</html>

Now you add cells and their values at run-time using the TableRow and TableCell class object (see Listing 7-28).

Listing 7-28. Adding table rows and cells programmatically 

            int rows = 3;
            int cols = 2;
            for (int j = 0; j < rows; j++)
            {
                TableRow r = new TableRow();
                for (int i = 0; i < cols; i++)
                {
                    TableCell c = new TableCell();
                    c.Controls.Add(new LiteralControl("row " + j.ToString() + ", cell " + i.ToString()));
                    r.Cells.Add(c);
                }
                Table1.Rows.Add(r);
            }

The example you saw in Listing 7-28 creates a table with three rows and two columns. You can also add rows and columns to a table programmatically. This program, which looks like Figure 7-58, adds rows and columns to a table at run-time based on the values entered in the text boxes. You create a Web application and add a control, two labels, and two text boxes to the page.

First, you create one <asp:Table> control to your .aspx page:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Creatingtableprogrammatically._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Table ID="Table1" runat="server">
        </asp:Table>
        Rows:
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
        Columns:
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Create Table" OnClick="Button1_Click" /><br />
    </div>
    </form>
</body>
</html>

Figure-7.58.jpg

Figure 7-58. Creating a table programmatically 

Next, add the code in Listing7-29 on the button-click handler.

Listing 7-29. Button-click handler create a table programmatically

        protected void Button1_Click(object sender, EventArgs e)
        {
            int rows = Convert.ToInt16(TextBox1.Text);
            int cols = Convert.ToInt16(TextBox2.Text);

            for (int j = 0; j < rows; j++)
            {
                TableRow r = new TableRow();
                for (int i = 0; i < cols; i++)
                {
                    TableCell c = new TableCell();
                    c.Controls.Add(new LiteralControl("row" + j.ToString() + ", cell " + i.ToString()));
                    r.Cells.Add(c);
                }
                Table1.Rows.Add(r);
            }
        }

Finally, run the application and enter the number of rows and the number of columns to the text boxes and then click the Create table button to create a table.

Conclusion

Hope this article would have helped you in understanding creating a table programmatically in ASP.NET. See other articles on the website also for further reference.

adobook.jpg
This essential guide to Microsoft's ADO.NET overviews C#, then leads you toward deeper understanding of ADO.NET.

Login to add your contents and source code to this article
share this article :
post comment
 

public void CreateTable() { // disconnected state // creating table dynamically DataTable dt = new DataTable("emptable"); DataColumn dc = new DataColumn("name",typeof(string)); DataColumn dc1 = new DataColumn("id",typeof(int )); DataColumn dc2 = new DataColumn("age",typeof(int)); DataColumn dc3 = new DataColumn("salary", typeof(double)); dt.Columns.Add(dc); dt.Columns.Add(dc1); dt.Columns.Add(dc2); dt.Columns.Add(dc3); DataRow dr = dt.NewRow(); dr[0] = "tarun"; dr[1] = 1 ; dr[2] = 21; dr[3] = 0; DataRow dr1 = dt.NewRow(); dr1[0] = "chara"; dr1[1] = 2; dr1[2] = 21; dr1[3] = 0; DataRow dr2 = dt.NewRow(); dr2[0] = "rupesh"; dr2[1] = 3; dr2[2] = 21; dr2[3] = 0; dt.Rows.Add(dr); dt.Rows.Add(dr1); dt.Rows.Add(dr2); GridView gd = new GridView(); gd.DataSource = dt; gd.DataBind(); form1.Controls.Add(gd); } protected void Page_Load(object sender, EventArgs e) { CreateTable(); }

Posted by Akshay Chara Feb 11, 2011
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Nevron Gauge for SharePoint
Become a Sponsor