Vinz' Blog

"Code, Beer and Music ~ my way of being a programmer"
posts - 129, comments - 469, trackbacks - 0

My Links

News

Archives

Image Galleries

I'm a...

I'm at...

FAQ: Dynamically Adding Rows in ASP Table on Button Click event

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 rows of TextBoxes in ASP Table on every click of the Button and retain the entered values on postbacks.

Here are the code blocks below:

ASPX:

<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="Add New Row" />

    </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:

CODE BEHIND:

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.


 

That’s it! Hope you will find this example useful!

Print | posted on Monday, June 29, 2009 2:27 AM |

Feedback

Gravatar

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event

This is exactly what I was looking for to use for one of my applications. The only problem I found is, it is not saving any of the data when I hit the add new rows button. Any suggestions? I had to move it into a pannel for it to work with my master pages and even without it being the the panel it would not save the information.

Thank you,

Stephen
6/30/2009 11:26 AM | Stephen
Gravatar

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event

Hi Stephen,

You can get the data as what I did in the SetPreviousData() method. Use Request.Form to grab the data from the TextBox and save it to your DB..
6/30/2009 8:04 PM | Vinz
Gravatar

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event

Wonderful, I was worried about my application and now you solved my problem.
Thanks
11/12/2009 8:16 PM | khizar
Gravatar

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event

@khizar,

Glad to be of help! :)
11/12/2009 10:36 PM | vinz
Gravatar

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event

Hi,

Thanks for your code.It works well. I modified the code to have a radiobutton control as well in the Cell and when i access the radio button value in SetPreviousData() method..all the radio buttons return checked=false. how do i get which radio button is checked after clicking on "Add New Row" button? Can you please give a solution.

Thanks,
Yuva
11/17/2009 7:24 AM | Yuva
Gravatar

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event

hi
I have to view data in aspx page at run time which looks like binary tree.how to do this.

Please help me. Its very urgent.

Thanks
Minakshi
12/3/2009 10:59 PM | minakshi
Gravatar

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event

the above code does not store the values of textbox if placed on content page holder. please help me out.
12/27/2009 10:25 PM | Varsha
Gravatar

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event

This code helped me lot, thank you so much.

thanks
kv
1/27/2010 11:11 PM | kv reddy
Gravatar

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event

The added table rows goes away on the click of another button
2/2/2010 4:18 PM | sep
Gravatar

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event

@sep,

Try to update your page load codes to this below:

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ViewState["RowsCount"] = numOfRows + 1;
}

if (Request.Form["Button1"] == null)
{
if (ViewState["RowsCount"] != null)
{
numOfRows = Convert.ToInt32(ViewState["RowsCount"].ToString());
GenerateTable(--numOfRows);
}
}
}
2/2/2010 5:49 PM | Vinz
Gravatar

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event

thanks, this code works. but when i'm adding a dynamically added button and on the click of that when i add the table, the rows are added twice
2/3/2010 4:05 PM | sep
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: