简体   繁体   中英

How do I place a control created in the code behind on a page?

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.

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM