Dynamically add server controls to a web page?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

How do I dynamically add web server controls to a web form? Also, how can I
position them?

Any sample code or links would be appreciated...
 
controls.add()

Now, you can do this a few ways, but I think the easiest is to use a
placeholder control, then you can add whatever you want to it, but the page
itself is also a control that you can directly add to..

Could I ask for a little more background though.. perhaps there are other
ways depending on what you are trying to do specifically...
 
To create controls and position them, what I usually do is (and these steps
I do in PAGE_LOAD):
1) Add a PlaceHolder control in the place on the page where I want the
server control to be.
2) Create the server control using Page.LoadControl.
3) Assign an id to the control. Make sure this id is unique within the
controls collection that this control will be added to.
4) Update the server control for display.
5) Add the created control(s) to the PlaceHolder.Controls collection.

And one hint:
- You have to do this process on a postback if you want to get data &
events out of the server control. So, on a postback, do steps 1, 2, 3, and
5; make sure you skip 4 otherwise you will overwrite any value getting
posted back. And, if you don't keep the id the same, you will not get any
data or events posted back.

Jeff
 
Example:

ControlContainerPanel is a empty Panel at the bottom of your webform.

TextBox myNewTextBox = new TextBox();
myNewTextBox.Text = "Default.Text";

ControlContainerPanel.Controls.Add(myNewTextBox);


You can add controls to a large number of objects like Page, TabelCells,
Panels and so on. With that in mind you can position them. Another way
that might work is to add some stylesheet information using the
myNewTextBox.Style.Add("LEFT", "160px");
myNewTextBox.Style.Add("TOP", "100px");
myNewTextBox.Style.Add("POSITION", "absolute");


Cheers,
//Rutger

http://www.RutgerSmit.com
 
We do a lot of surveys and tests. Well, I want to dynamically add questions
and the answer to the question will be determined by the way the the admin
person set up the question. The answer could be a radio button, check box or
even text box. The questions and answers are out on a data base by
survey/test. The admin person will set up a survey/test and add answers to
the test/survey.
 
This has actually been posted a number of times lately...for this exact
scenario.
My recommendation is a Repeater with a label and placeholder control in it.
The label is for the Question and the placeHolder is for the control.
You get the question list, bind it to the repeater, and plop in the
appropriate stuff in the Item_DataBound() call of the repeater.

hth

--
Curt Christianson
site: http://www.darkfalz.com
blog: http://blog.darkfalz.com
 
Back
Top