Geeks With Blogs

News

Microsoft MVP


DZone MVB


Moderator at CodeASP.NET


Quiz Master







free counters
Free counters
Added on January 19,2012


Follow Me @vmsdurano

A bit About Me



Disclaimer
The opinions expressed herein are my own personal opinions and does not represent the opinions of my employers. Nor does it represent the opinion of my dog, because I don’t have one.


Vinz' Blog (ProudMonkey) "Code, Beer and Music ~ my way of being a programmer"

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!

 

Technorati Tags: ,,
Posted on Monday, June 29, 2009 2:27 AM ASP.NET , C# | Back to top


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

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event
Requesting Gravatar...
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
Left by Stephen on Jun 30, 2009 11:26 AM

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event
Requesting Gravatar...
Wonderful, I was worried about my application and now you solved my problem.
Thanks
Left by khizar on Nov 12, 2009 8:16 PM

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event
Requesting Gravatar...
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
Left by Yuva on Nov 17, 2009 7:24 AM

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event
Requesting Gravatar...
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
Left by minakshi on Dec 03, 2009 10:59 PM

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event
Requesting Gravatar...
the above code does not store the values of textbox if placed on content page holder. please help me out.
Left by Varsha on Dec 27, 2009 10:25 PM

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event
Requesting Gravatar...
This code helped me lot, thank you so much.

thanks
kv
Left by kv reddy on Jan 27, 2010 11:11 PM

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event
Requesting Gravatar...
The added table rows goes away on the click of another button
Left by sep on Feb 02, 2010 4:18 PM

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event
Requesting Gravatar...
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
Left by sep on Feb 03, 2010 4:05 PM

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event
Requesting Gravatar...
hi,
i have replaced the textbox with dropdownlist.i want to populate different values for the three drpdown list .can u tell me plz?
Left by saran on Feb 10, 2010 9:01 PM

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event
Requesting Gravatar...
Hi,
I used your code. But when i use it exactly the same way (that is adding a new table on form dynamically) it works fine.

but when i added the table to an already defined Panel or if i try to add rows to a already defined Table using ur code, it creates the table but does not populate the old values.

Please help

Sunil
Left by Sunil on Apr 29, 2010 3:05 PM

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event
Requesting Gravatar...
Hi,

I have modified your code according to my form, i was using the Tabs in my page, so it required some modifications to FindControl of the table to which i was adding my rows. So did some serious debugging and finally made it work for me. All thanks to your code Man. You rock.

This code works really well. I required 2 tables in my page for which the rows needed to be generated dynamically (separately though). So i made the changes as you suggested (for 'onclick' of some other button) and it is working fine for both the tables. Thanks a lot
God Bless you.
Left by Sunil on Apr 30, 2010 4:05 PM

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event
Requesting Gravatar...
hi,
i had make a site with asp.net and i don't know how to access it from my computer locally

like
\\ websitname

take in mind i have made it with visual studio 2010
is it possible to add server controls in button click ? How ?

Best Regards,
Left by moayed on Jun 17, 2010 8:26 PM

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event
Requesting Gravatar...
hi,I am raomingfor this type of code.I have used this code,its working fine if the page doesnt have Masterpage.It is nt working when i place in contentPlaceholder.controls are nt displaying values,,and textboxes are displaing bottom of the page and for every click on Addbutton,,Page is distruping..Can you Give any solution Please..
Left by Lara on Dec 01, 2010 1:31 PM

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event
Requesting Gravatar...
@All,

Just recently blogged about the fix for this in Masterpage here: http://geekswithblogs.net/dotNETvinz/archive/2010/12/03/master-page-dynamically-adding-rows-in-asp-table-on-button.aspx
Left by Vinz on Dec 03, 2010 8:37 PM

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event
Requesting Gravatar...
can i add this table in wizard control..................i mean Page.Form.Controls.Add(table)....Wizard1.Controls.Add(table) not work.
Left by Manish on May 12, 2011 2:35 AM

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event
Requesting Gravatar...
@Manish,

AFAIK, a Wizard control is composed of WizardSteps. So try to add the control within WizardStep.
Left by Vinz on May 12, 2011 4:19 PM

# re: FAQ: Dynamically Adding Rows in ASP Tablevente on Button Click
Requesting Gravatar...
your coding creating row dynamically but i want to put value in all the textbox
taking from the database .how could i do it.
Left by Mithun Patra on May 27, 2011 2:57 PM

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event
Requesting Gravatar...
love ya! :D
Left by schatzii on Aug 16, 2011 7:52 PM

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event
Requesting Gravatar...
Thanks for this nice post.
I need help.
I need to add 3 textbox, 1 dropdownlist, 1 fileupload and 1 checkBox in a row.

Left by vikender on Aug 30, 2011 3:30 PM

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event
Requesting Gravatar...
How do I save the values when I click the button to add a new row?
Left by Steph on Sep 16, 2011 9:36 AM

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event
Requesting Gravatar...
Thank u for helping me.... it really works....
Left by jithin on Sep 17, 2011 6:42 PM

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event
Requesting Gravatar...
PLease help me to delete selected row using checkbox of dynamically created Table in asp.net.
Left by Delete Dynamically Created Row on Apr 23, 2012 7:23 PM

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event
Requesting Gravatar...
It's good..
But I have 1 requirement..
How you can add rows to gridview in one page( say 2nd page ) when i click a button in another page(i.e 1st page ).
In 1st page I have textboxes from which data should go to
2nd page through datarow object.
Left by v kumar on May 17, 2012 8:51 PM

# re: FAQ: Dynamically Adding Rows in ASP Table on Button Click event
Requesting Gravatar...
Thanks for the post,it helped me a lot
Left by swathi on Dec 10, 2012 7:54 PM

comments powered by Disqus

Copyright © Vincent Maverick Durano | Powered by: GeeksWithBlogs.net