How to dynamically create a control in a user control?

Q

Quentin Huo

Hi:

I have a user control and I want to dynamically create a Label control and
TextBox control when the button "add more author name" is clicked.

I did like this:

1. there is a "PlaceHolder" control "ph" in the user control;

2. create a Label control and TextBox control when in the "add" button
event, like:
Label lblAuthor = new Label();
lblAuthor.Text="Author";


TextBox tbAuthor = new TextBox();

tbAuthor.ID="...";



3. add the controls to the PlaceHolder control "ph":

ph.Controls.Add(lblAuthor);
ph.Controls.Add(tbAuthor);


But it doesn't work, the value that is typed into the new-created TextBox
control cannot be kept by form(the form tag is in the parent page that
includes the user control). When click another button like "save", the value
will be losted. Where is the problem? How to fix it?

Thanks

Q.
 
K

Konrad Rotuski

you need to recreate control hierarchy on each postback before ViewState is
retained for dynamically added controls

HTH

Konrad
 
S

Sayed Hashimi

Quentin,

The reason it doesn't work is that the server-side event that adds the
new controls to the place holder gets fired late in the event chain.
There is nothing you can do about that. I don't think it would help
for me to go deep into this, so I will just give you an alternative
solution. I suggest that you use a datagrid rather than a place
holder. It is fairly easy to add new rows to the datagrid rather than
have to overcome the problem you have with the place holder. Let me
point you to a few articles that discuss dynamically adding rows to a
datagrid. The point to remember with adding new rows to a datagrid is
that you add a new row to the data source of the grid and then rebind
and that takes care of it.

http://www.dotnetjunkies.com/Tutorial/C0DD0D9A-8907-4117-BBF2-4C407AA83574.dcik
http://www.123aspx.com/ResPrint.aspx?res=359



sayed
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top