Reputation: 417
protected void Page_Load(object sender, EventArgs e)
{
Label myLabel = new Label();
myLabel.Text = "Testing 1 2 3";
}
If I create this Label object in the code behind, and it has no < asp:Label > tag on the main page, how can I put this Label somewhere on the page?
I want to dynamically create controls based on information out of a database. From there, I want to place the controls onto the webpage. I can't predefine places for them because the number and types of controls will change.
What's the best way to do this?
What if I already have something on my page, such as a table, and I wanted to place the control after the end of the table.
Upvotes: 1
Views: 5121
Reputation: 1
If you use a Placeholder, you could then add as many controls to it as you'd like. If you assign a CSS to each control, you can then easily place the controls anywhere you want on the page.
Label myLabel = new Label();
myLabel.Text = "Testing 1 2 3";
myLabel.cssClass ="myClass1"
Label myLabel2 = new Label();
myLabel2.Text = "Testing 4 5 6";
myLabel2.cssClass ="myClass2"
plHolder.controls.add(myLabel)
plHolder.controls.add(myLabel2)
Upvotes: 0
Reputation: 460288
You must add it to the page's control-collection somewhere.
this.Controls.Add(myLabel);
Instead of adding it directly to the page, i would use PlaceHolders
or Panels
as container control. You need to recreate dynamically created controls on every postback in page_load
at the latest with the same ID as before(to reload ViewState and trigger events).
You should use CSS to control the layout of the controls.
An alternative approach would be to use a web databound control like Repeater
which is easier and maintains controls and their state automatically.
Upvotes: 4