BarryFanta
BarryFanta

Reputation: 69

Multiple instances of server control attached programmatically not appearing?

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();
        lblNone.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?

Upvotes: 0

Views: 174

Answers (2)

Andre Pena
Andre Pena

Reputation: 59456

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

Upvotes: 1

Plip
Plip

Reputation: 1038

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.

Upvotes: 1

Related Questions