简体   繁体   English

如何将代码中创建的控件放在页面上?

[英]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? 如果我在后面的代码中创建了这个Label对象,并且在主页面上没有<asp:Label>标签,那么如何将此Label放在页面的某个位置?

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. 我不会将其直接添加到页面中,而是使用PlaceHoldersPanels作为容器控件。 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). 您需要最迟在page_load中的每个回发上重新创建动态创建的控件,其ID与之前相同(重新加载ViewState和触发事件)。

You should use CSS to control the layout of the controls. 您应该使用CSS来控制控件的布局。

An alternative approach would be to use a web databound control like Repeater which is easier and maintains controls and their state automatically. 另一种方法是使用像Repeater这样的Web数据绑定控件 ,它更容易并自动维护控件及其状态。

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. 如果为每个控件分配一个CSS,则可以轻松地将控件放在页面上的任何位置。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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