Creating and accessing at runtime created controls


For a website I am creating I need to create textboxes at runtime depending from the value inserted in a textbox, when the number is entered there should be created a table (or something alike) with x rows each having for example 4 textboxes. I managed to create a table with the textboxes but I cannot address them from my code behind (C#). I have allready tried it 2 ways...

The first was using literal controls, but the alignment wouldnt work...


1    PlaceHolder ph = new PlaceHolder();
2 LiteralControl openrij = new LiteralControl("&lt;tr><td>");
3 LiteralControl sluitcel = new LiteralControl("&lt;/td><td>");
4 LiteralControl sluitrij = new LiteralControl("&lt;/td></tr>");
5 this.Generiek.Controls.Add(new LiteralControl(@"&lt;table border='1'>"));
6 ph.Controls.Add(new LiteralControl("&lt;table><tr><th>Datum</th><th>Begin</th><th>Einde</th><th>Expert</th><th>Afgelast</th><th>Vrijgegeven</th><th>Seizoen</th></tr>"));
7 8 for (int i = 1; i <= Convert.ToInt16(txtAantal.Text); i++)
9 {
10 TextBox txtDatum = new TextBox();
11 TextBox txtBeginUur = new TextBox();
12 TextBox txtEindUur = new TextBox();
13 TextBox txtExpert = new TextBox();
14 CheckBox chkAfgelast = new CheckBox();
15 CheckBox chkVrijgegeven = new CheckBox();
16 TextBox txtSeizoen = new TextBox();
17 txtDatum.Attributes.Add("runat", "server");
18 txtDatum.ID = String.Concat("txtNaam" + i);
19 20 ph.Controls.Add(openrij);
21 ph.Controls.Add(txtDatum);
22 ph.Controls.Add(sluitcel);
23 ph.Controls.Add(txtBeginUur);
24 ph.Controls.Add(sluitcel);
25 ph.Controls.Add(txtEindUur);
26 ph.Controls.Add(sluitcel);
27 ph.Controls.Add(txtExpert);
28 ph.Controls.Add(sluitcel);
29 ph.Controls.Add(chkAfgelast);
30 ph.Controls.Add(sluitcel);
31 ph.Controls.Add(chkVrijgegeven);
32 ph.Controls.Add(sluitcel);
33 ph.Controls.Add(txtSeizoen);
34 ph.Controls.Add(sluitrij);
35 }
37 Generiek.Controls.Add(ph);
And the other was using a table control, but here i can't address my textboxes...
1        protected void cmdGenereer_Click(object sender, EventArgs e)
2 {
3 Table tbl = new Table();
4 TableRow row = new TableRow();
5 TableCell datum = new TableCell();
6 datum.Text = "Datum";
7 row.Cells.Add(datum);
8 TableCell beginuur = new TableCell();
9 beginuur.Text = "Beginuur";
10 row.Cells.Add(beginuur);
11 TableCell einduur = new TableCell();
12 einduur.Text = "Einduur";
13 row.Cells.Add(einduur);
14 TableCell expert = new TableCell();
15 expert.Text = "Expert";
16 row.Cells.Add(expert);
17 TableCell afgelast = new TableCell();
18 afgelast.Text = "Afgelast";
19 row.Cells.Add(afgelast);
20 TableCell vrijgegeven = new TableCell();
21 vrijgegeven.Text = "Vrijgegeven";
22 row.Cells.Add(vrijgegeven);
23 TableCell seizoen = new TableCell();
24 seizoen.Text = "Seizoen";
25 row.Cells.Add(seizoen);
26 tbl.Rows.Add(row);
27 28 for (int i = 1; i <= Convert.ToInt16(txtAantal.Text); i++)
29 {
30 TableRow invoerRow = new TableRow();
31 TableCell celDatum = new TableCell();
32 TextBox txtDatum = new TextBox();
33 celDatum.Controls.Add(txtDatum);
34 invoerRow.Cells.Add(celDatum);
35 TextBox txtBeginUur = new TextBox();
36 TableCell celBeginUur = new TableCell();
37 celBeginUur.Controls.Add(txtBeginUur);
38 invoerRow.Cells.Add(celBeginUur);
39 TextBox txtEindUur = new TextBox();
40 TableCell celEindUur = new TableCell();
41 celEindUur.Controls.Add(txtEindUur);
42 invoerRow.Cells.Add(celEindUur);
43 TextBox txtExpert = new TextBox();
44 TableCell celExpert = new TableCell();
45 celExpert.Controls.Add(txtExpert);
46 invoerRow.Cells.Add(celExpert);
47 CheckBox chkAfgelast = new CheckBox();
48 TableCell celAfgelast = new TableCell();
49 celAfgelast.Controls.Add(chkAfgelast);
50 invoerRow.Cells.Add(celAfgelast);
51 CheckBox chkVrijgegeven = new CheckBox();
52 TableCell celVrijgegeven = new TableCell();
53 celVrijgegeven.Controls.Add(chkVrijgegeven);
54 invoerRow.Cells.Add(celVrijgegeven);
55 TextBox txtSeizoen = new TextBox();
56 TableCell celSeizoen = new TableCell();
57 celSeizoen.Controls.Add(txtSeizoen);
58 invoerRow.Cells.Add(celSeizoen);
59 txtDatum.Attributes.Add("runat", "server");
60 txtDatum.ID = String.Concat("txtNaam" + i);
61 tbl.Rows.Add(invoerRow);
62 63 64 Generiek.Controls.Add(tbl);
65 }
I use this line to access my controls in the last example...
first I want to get the table ==> Table tabel = (Table)Generiek.FindControl("tabel");
addressing the controls ==> 
for (int i = 1; i <= Convert.ToInt16(txtAantal.Text); i++)
String datumVeld = String.Concat("ctl00_MainContent_txtDatum" + i);
datum = Convert.ToDateTime(((TextBox)tabel.Rows[i].FindControl(datumVeld)).Text);

 I don't see what would be the best solution... If any other solution is possible, please let me know...
 Thanks in advance,
4/30/2008 6:08:52 PM 93655 articles. 6 followers. Follow

9 Replies

Similar Articles

[PageSpeed] 34


The problem is that you are creating the controls in the page behind, they are not persisted to the next postback - normally. You need to do a few tricks to get them to load.

I recently replied to another developer that was having a similar problem.  You will need to modify the code to suit your needs but it basically allows you to create controls dynamically in the code behind and then access them on the postback. The trick is that they have to be re-created and then loaded with the viewstate etc.

Let me know how it goes
Good Luck



4/30/2008 10:21:01 PM

Or you could accomplish the same thing with almost no coding using the repeater control

If you add a repeater to your page,  like this:


            <asp:Repeater ID="rpt" runat="server">
                    <tr><asp:TextBox ID="txt" runat="server"></asp:TextBox></tr>


You could then bind it like this in the code:


1            int numberOfTextboxes = 10;
2            List<int> dataSource = new List<int>();
3            for (int i = 0; i < numberOfTextboxes; i++ )
4            {
5                dataSource.Add(i);
6            }
8            this.rpt.DataSource = dataSource;
9            this.rpt.DataBind();
And that's all there is to it. 
My Blog
5/1/2008 8:18:24 AM

So if I use the repeater like you said, I must "predeclare" the textboxes in the repeater? And how about accessing them afterwards? Lets say I need 3 textboxes on each row "txtname" "txtage" and "txtaddress"... And I need to add 4 persons to the db...

<tr><td><asp: textbox ID="txtname" runat="server"></asp:textbox></td>
<td><asp: textbox ID="txtage" runat="server"></asp:textbox></td>
<td><asp: textbox ID="txtaddress" runat="server"></asp:textbox></td></tr>

the code behind you wrote will be the same except 10 becomes 4, I think?
and the dataSource.Add(i); makes sure the textboxes are named txtname0, txtname1 and txtname2?

How do I access the values of these textboxes afterwards?
Is it something like:  (TextBox)rpt.findControl("txtname0").Text? 

Thanks for your help allready, I think I might go for the repeater... 

 Edit: maybe a stupid question, but from your answer I conclude I don't need to postback to be able to add and use the textboxes?

5/1/2008 3:52:13 PM

No- there's no need to declare them statically- the repeater will 'repeat' the markup in the ItemTemplate once for every row/item in your data source- hence the code I posted before will create a number of table rows- each containing a textbox.

You can access the textboxes on postback by looping through the repeater rows, and using FindControl as in the code you posted, except that you should call FindControl on the repeater row (item) rather than on the repeater itself. i.e.:


        TextBox txt = null;
        foreach (RepeaterItem item in this.rpt.Items)
            txt = item.FindControl("txt") as TextBox;
Alternatively, if the control which causes the postback is within the repeater's itemtemplate you can hook up to the ItemCommand event and in this case a reference to the repeater item which causes the postback is returned via the event arguments. 
My Blog
5/1/2008 10:15:59 PM

Hi check these urls 

Santosh kumar
Mark as Answer on the post that helped you.

5/1/2008 10:27:31 PM


You create control dynamicly, when the page post back to server, the dynamic will disappear.

You should recreate these dynamic control at Page_load or Page_init() function everytime.

    protected void Page_Load(object sender, EventArgs e)

// create these dynamic control.


Or you can store these control, and restore them after postback.

    protected void Button4_Click(object sender, EventArgs e) {
        Panel tt 
= new Panel();
TextBox tb = new TextBox();
tb.ID "txtName";
tb.Text "hello";
protected void Page_Load(object sender, EventArgs e) {
if ((Cache("tt"!= null)) {
            Panel tt 

If you want to find these dynamic control, please use the following method.

TextBox txt=this.form1.FindControl("dynamicTextBox") as TextBox;


selectedValue = Request.Form["dynamicTextBox"].ToString();

Let me know if I have misunderstood what you mean.
Hope it helps,
Hua Jun

Hua Jun Li
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
5/2/2008 2:44:02 AM

I have noticed quite a number of posts over the last few days when the original poster asks a question relating to dynamic controls, and where it seems their problem could be solved without needing to resort to these in the first place. As everyone who has worked with dynamic controls will testify- it can quickly lead to some very ugly code, as you have to (as mentioned) re-create them on each postback.

If the scenario becomes more complicated, and you need to show different controls based on the current state etc, you quickly find the UI codebase turning into spaghetti.

I am not claiming that dynamic controls are not useful: there are some circumstances where they are necessary (for example, a site that stores the layout for its pages in a database and generates the pages on-the-fly), however unless there is a specific need for them and one of the existing controls cannot be used, or coerced into, doing what you want, I would say give them a miss.

My Blog
5/2/2008 8:45:27 AM

Thanks, I solved it with the repeater control... It works great... But what I don't get, is why a List of integers are created and then linked as a datasource... Is it just because there are multiple rows and/or items on that row? Probably it was a stupid question, but I want to understand what the code does...

Thanks again,


5/2/2008 9:11:40 PM


Sorry- I didn't see your question earlier.

There was no special reason for using a list of integers- the only requirement is that you use a datasource which implements the IEnumerable interface (all databinding controls require that the datasource is enumerable).

So a list of integers was just a quick way of creating an enumerable datasource (because generic lists implement IEnumerable, as do arrays, datatables etc)- however the contents were not relevant in this instance. In many cases, the contents are relevant. For example, if you bind a datatable to a repeater, you will want to display the contents of the datatable within your repeater controls, which you could do by hooking up to the ItemDataBound event and adding some code like this:

Label lbl = (Label)e.Item.FindControl("myLabel");
lbl.Text = DataBinder.Eval(e.Item.DataItem, "MyDataTableFieldName").ToString();
However, if you are only interested in the number of rows displayed to the user- not the contents of the datasource itself, then a list or array of integers/strings/whatever, is a quick way to create a valid enumerable datasource which can be databound. So in this case, it is not the contents of the datasource which were relevant, but rather the number of items within the list.


My Blog
5/15/2008 10:35:58 AM

Similar Artilces:

Problem in accessing web form data in user controls when create user control dynamically
HI. I have a problem using web user control. I designed a user control named NewsForm. This user control contains some web form elements like <asp:textbox>. When I add it in an .ASPX page, all things may be true. I can know which user filles in textbox (for example and other controls) <%@ Register TagPrefix="uc1" TagName="NewsForm" Src="NewsForm.ascx" %> and <UC1:NewsForm id="newsForm" runat="server"></UC1:NewsForm> But when i create it in code behined dynamically, however user control has web form controls but their value are blank for example //aspx co...

Creating and accessing controls created with loop
Hello guys, I have got this dropdown list that allows a person to select the number of things he wants to enter, and from then on, textboxes will appear depending on the number of things he wants. I have no problems creating them, but how do I access whatever is typed in them? Since all of them have the same name. Here's my code: Dim a As New TextBox For i = 1 To j Me.FindControl("Form1").Controls.Add(a) Next Any help greatly appreciated. Thanx Give "a" a unique id....when you create the control. Dim a As New TextBox For i = 1 T...

Create dynamic form and form controls inside a table at runtime
I'm migrating a Classic ASP application.  The application migration is supposed to keep the same look and feel of the existing application.  I.E. as we roll out parts of the application the user has no idea that we've made any changes.  The basic direction is "Change it, but we don't want to see it change in any way." The User Control is a datagrid on steroids and then some.  It extends the basic datagrid concept with much more functionality.  We went this route because the basic premise is to maintain the existing look and feel.  For exam...

Access runtime created controls.
 Hello All, I have created some text boxes at the runtime, now I want to get the text of these textboxes in another function Sample :     protected void Button2_Click(object sender, EventArgs e)    {         Textbox Textbox1 = new Textbox();         Textbox1.ID = "Textbox1";    }    protected void Button1_Click(object sender, EventArgs e)    {                String MyCmd ...

Create form control at runtime
Hi, I need help to create the following form at runtimeI am getting the data from Database Tables Gender Table: LKP_GenderAge Table: LKP_AgeGroup I need the form to be created at runtime in case I need to store data from other tables Can any one help me with this? ___________________________________________________________________________________________   Gender/ Age |                          15-25       &nb...

User Control controls not created when dynamically creating user control
  Have created a user control for displaying and editing a dynamically number of values. The user control contains two labels and an edit box. When dynamically loading the user control I get an error when the control itself tries to change setting on the fields within the user control.   Why doesnt this work? It works okay if I dont load it dynamically but create a user-control-instance in the aspx-page but thats no solution.   Thankyou!     Here is my code:   ucDataValue.ascx   <%@ Control Language="C#" AutoEventWireup="true&...

How to access a control on a web form from anoter web form
hi all I have this scenarios i have two web forms, one called form1 and the other called form2 form1 has a label with id "lbl1" is it possible to access lbl1 from form2, change its text permenantly? thanks.   refer: remember to click "Mark as Answer" on the post that helps you. MinaSamy: hi all I have this scenarios i have two web forms, one called form1 and the other called form2 form1 has a label with id "lbl1" is it p...

Accessing Control Value created at Runtime
Hi All I am creating some textbox controls at runtime inside a UserControl named as AddressMaintenance.ascx i want to know how can i get the value of these TextBoxes entered by user since these controls are created at runtime. Please any sort of help will be of great help Any Code or link will work Thanks and Regards Amit Goel If you dynamically add the controls in Page_Load or earlier, then, when you re-add them on postback, their values should be populated for retrieval in any event handlers that you've wired later in the page processing flow. Hi Amit, ...

how to create a web user control in runtime?
I created a web user control that want to use it in a page for many times. In other words, I want to do the similar thing to my web user control as following:       Dim newbutton as new Button     newButton.Text = "New Button"         Page.Controls.Add(newButton) But when I use:  Dim myControl as myUserControl  It will comes out error. Can anybody help? Thanks!   I finally find out the correct class name for the user control now. because my web user control is under a fo...

Dynamically creating controls in Web forms
I am able to create a web control programmatically and display on the form. In the click event of the button then I am trying to capture the value entered in the above created textbox in another click of button but I am unable to obtain the reference of the control that has been created dynamically. Can anyone help me please? protected System.Web.UI.WebControls.Panel myPanel; private void btnMake_Click(object sender, System.EventArgs e) { TextBox txtBox = new TextBox(); myPanel.Controls.Add(txtBox); } private void btnGotValues_Click(object sender, System...

Dynamically created controls in web form
Hi there. This is bit of an open ASP.Net (C#) question with regards to dynamically created controls and in particular tabular or panel controls. What I currently have is a web page that creates between 1 and 6  tables, each of which holds specific data about a set of products, each table (or panel, if you want) has a couple of multi-line TextBoxes and a few other controls, all lined up in a set format. The number is determined by the data records returned from a database table. My question is what is a best way to create these tables of data at run time?  Has anybody else had e...

Accessing Dynamically Created Web Controls
I am importing a CSV file into a DataTable.  I am then adding a column that contains a picklist into the DataTable before displaying it.  Well that worked great...BUT I have no idea how to access the values in the picklists I created  <sigh> Displays data: void LoadData() { // IMPORT CSV FILEOleDbConnection ExcelConnection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filetoread +";Extended Properties=Text;");     OleDbCommand ExcelCommand = new OleDbCommand(@"SELECT top 50 * FROM test.csv",ExcelConnection);   &...

Access Dynamically created controls on a Form?
Radio Buttons are added to my form During the Load event, the quantity determined by User input. They are placed in pairs on groupboxes with code like this: (edited a bit for brevity) Public Function LayoutForm(ByVal intNumber As Integer) Dim intCount As Integer Panel1.Controls.Clear() For intCount = 1 To intGames 'Visitors Button Dim RadioButton1 As System.Windows.Forms.RadioButton RadioButton1 = New System.Windows.Forms.RadioButton RadioButton1.Text = GetSchedule(intWeek, "Visitor", intCount) ...

controlling access to the create new bug form
Hi All, I am trying to find a way to control permissions on the create bug form. Basically i don't want all my users to be able to set/edit certain fields such as "target", "assigned to" etc in the crete new bug form. Ideally i would want a way to assign this restriction on certain groups, including the "guest" accounts. Is there a way of implementing this? TIA On May 20, 6:25=A0pm, wrote: > Hi All, > > I am trying to find a way to control permissions on the create bug > form. Basically i don't want all my...

Web resources about - Creating and accessing at runtime created controls -

Highest Percentage Of Opera Mini Users Accessing Facebook? Macau
If you were asked to guess which country had the highest percentage of users of Opera mobile Web browser Opera Mini users accessing Facebook ...

International Users Accessing Facebook Places Through US VPN Accounts
By using a virtual private network (VPN) hosted in the United States, Facebook users from around the world are accessing Facebook Places. The ...

What are some alternatives to Yodlee for accessing bank information?
Clay Loveless , Founder, Jexy. Co-founder, Mashery. Founder, Jexy. Co-founder, Mashery.

Cloud Console - Accessing files in cloud storage for iPad on the iTunes App Store
Get Cloud Console - Accessing files in cloud storage on the App Store. See screenshots and ratings, and read customer reviews.

Meryl Streep On Accessing The Characters Within - YouTube
Meryl Streep talks about the importance of an actors work representing their ability. CONNECT WITH AFI: ...

Student pleads guilty to accessing records about Frances Abbott design scholarship
The Sydney student who leaked information about a fashion school scholarship controversially awarded to the daughter of the Prime Minister has ...

Accessing a headline opinion
Accessing a headline opinion

Sharp increase in authorities accessing private data
Australian law enforcement and government agencies have sharply increased their access without warrant to vast quantities of private telephone ...

Former librarian charged with accessing student records of Frances Abbott
A former part-time librarian at a Sydney design school has been charged after she allegedly accessed student records of Prime Minister Tony Abbott's ...

Frances Abbott scholarship: Sydney woman pleads guilty to accessing Whitehouse Institute records on PM's ...
A Sydney woman who leaked the student records of Tony Abbott's daughter pleads guilty. A Sydney woman who leaked the student records of Prime ...

Resources last updated: 12/26/2015 3:04:12 AM