ASPSnippets

Alerts
Get notified when a new article is published.

Name
 
Email

Your email will always be private and will not be shared.

Follow us on twitter.
 
FAQ: Dynamically Adding Rows in ASP Table on Button Click event
Author Name: Vinz Published Date: August 02, 2009
Filed Under :
ASP.Net
Views: 3081

I decided to write this simple example because I always encounter this kind of issue at the asp.net forums including this thread: http://forums.asp.net/t/1440947.aspx.

 

Basically this demo shows on how to generate ASP Table rows and columns on every click of the Button and retain the entered values on postbacks.

 

Here are the code blocks below:

 

ASPX:

 

<!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>Dynamic Adding of Rows in ASP Table Demo</title>

</head>

<body>

    <form id="form1" runat="server">

    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />

    </form>

    </body>

</html>

 

 

As you can see, the webform only contain a single Button. Now let’s create the methods for generating the Rows. Here are the code blocks below:

 

using System;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

public partial class _Default1 : System.Web.UI.Page

{

    //A global variable that will hold the current number of Rows

    //We set the values to 1 so that it will generate a default Row when the page loads

    private int numOfRows = 1;

  

    protected void Page_Load(object sender, EventArgs e)

    {

        //Generate the Rows on Initial Load

        if (!Page.IsPostBack)

        {

            GenerateTable(numOfRows);

        }

    }

 

    protected void Button1_Click(object sender, EventArgs e)

    {

        if (ViewState["RowsCount"] != null)

        {

            numOfRows = Convert.ToInt32(ViewState["RowsCount"].ToString());

            GenerateTable(numOfRows);

        }

    }

 

    private void SetPreviousData(int rowsCount, int colsCount)

    {

        Table table = (Table)Page.FindControl("Table1");

        if (table != null)

        {

            for (int i = 0; i < rowsCount; i++)

            {

                for (int j = 0; j < colsCount; j++)

                {

                    //Extracting the Dynamic Controls from the Table

                    TextBox tb = (TextBox)table.Rows[i].Cells[j].FindControl("TextBoxRow_" + i + "Col_" + j);

                    //Use Request objects for getting the previous data of the dynamic textbox

                    tb.Text = Request.Form["TextBoxRow_" + i + "Col_" + j];

                }

            }

        }

    }

 

    private void GenerateTable(int rowsCount)

    {

 

        //Creat the Table and Add it to the Page

        Table table = new Table();

        table.ID = "Table1";

        Page.Form.Controls.Add(table);

 

        //The number of Columns to be generated

        const int colsCount = 3;//You can changed the value of 3 based on you requirements

 

        // Now iterate through the table and add your controls

 

        for (int i = 0; i < rowsCount; i++)

        {

            TableRow row = new TableRow();

            for (int j = 0; j < colsCount; j++)

            {

                TableCell cell = new TableCell();

                TextBox tb = new TextBox();

 

                // Set a unique ID for each TextBox added

                tb.ID = "TextBoxRow_" + i + "Col_" + j;

                // Add the control to the TableCell

                cell.Controls.Add(tb);

                // Add the TableCell to the TableRow

                row.Cells.Add(cell);

            }

 

            // And finally, add the TableRow to the Table

            table.Rows.Add(row);

        }

 

        //Set Previous Data on PostBacks

        SetPreviousData(rowsCount, colsCount);

 

        //Sore the current Rows Count in ViewState

        rowsCount++;

        ViewState["RowsCount"] = rowsCount;

 

 

    }

}

 

 

 

As you can see the code above was pretty straight forward and self explanatory. Running the code above will give this output below in the page.


Adding Rows to ASP.Net Table Dynamically



That’s it! Hope you will find this example useful! Download the related sample using the link below.


Generate_Dynamic_Rows_in_ASP_Table.zip (1.89 kb)


If you like this article, help us grow by bookmarking this page on any social bookmarking site.
Bookmark and Share Page copy protected against web site content infringement by Copyscape

Related Articles

Comments

Add Comments

You can add your comment about this article using the form below. Make sure you provide a valid email address
else you won't be notified when the author replies to your comment

Please note that all comments are moderated and will be deleted if they are
  • Not relavant to the article
  • Spam
  • Advertising campaigns or links to other sites
  • Abusive content.
There is no need to add BR tags. Simply press enter for new line

Name*  
Email*
Comment*  
Security code
Security code