views:

58

answers:

2

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?

+1  A: 

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

Ciwee
+1  A: 

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.

Plip