开发者

Multiple instances of server control attached programmatically not appearing?

开发者 https://www.devze.com 2022-12-11 17:43 出处:网络
In the code behind of my page I want to attach a label in multiple places. To achieve this and avoid creating mutliple instances of the same label I\'ve tried:

In the code behind of my page I want to attach a label in multiple places. To achieve this and avoid creating mutliple instances of the same label I've tried:

        Label lblNone = new Label();
        lb开发者_Python百科lNone.Text = "<br/> None. <br/>";

        Master.mainContent.Controls.Add(lblNone);
        Master.mainContent.Controls.Add(lblNone);
        Master.mainContent.Controls.Add(lblNone);

For some reason I only see 1 instance of the "None." on my page?

Why is this?


You have no option.. you need to create one instance of Label for each control you want to see in the screen.

This is because of the behavior of the ControlCollection class.

  1. it will not allow multiple adds of the same "reference".
  2. When you add a control to one ControlCollection it is automatically removed from the previous so, even if you were adding your label to different ControlCollections it wouldn't work.

PS: By ControlCollection I mean the type of the property Master.mainContent.Controls


You might find it easier to create a method for this as so: -

protected void Page_Load(object sender, EventArgs e)
{
    this.Controls.Add(CreateLiteral("text"));
    this.Controls.Add(CreateLiteral("text"));
    this.Controls.Add(CreateLiteral("text"));
}

private Literal CreateLiteral(string Content)
{
    Literal L = new Literal();
    L.Text = Content;
    return L;
}

Thanks,

Phil.

0

精彩评论

暂无评论...
验证码 换一张
取 消