J.B.
J.B.

Reputation: 278

Add multiple controls to panel in webforms

I would like to be able to add multiple label controls to a panel and display them on an onlick event. The code I have does what I want it to the first time, then the label is simple replaced with a new label on the second onlick event and so on.

Here is what I have so far:

 private void createTaskLabel(Guid GoalID, string Goal)
 { 
     Label taskLabel = new Label();
     taskLabel.ID = GoalID.ToString();
     taskLabel.Text = Goal.ToString();
     TaskPanel.Controls.Add(taskLabel);
 }

So, for instance, this creates a new label with a uniqueID (handled elsewhere) and places it within the panel and displays it. When the onlick fires again, the same label is simply replaced instead of a new one appearing below it.

Upvotes: 1

Views: 3431

Answers (3)

Ravi Parashar
Ravi Parashar

Reputation: 11

Dim lbl As New Label Dim lbl1 As New Label Dim txt As New TextBox Dim txt1 As New TextBox

    lbl.Text = "Name"
    lbl1.Text = "class"
    Me.Controls.Add(lbl)
    Me.Controls.Add(txt)
    Me.Controls.Add(lbl1)
    Me.Controls.Add(txt1)

Upvotes: 1

Jimmy Chandra
Jimmy Chandra

Reputation: 6580

Have you look at Repeater control? It might make it a bit easier to implement I think. At least you don't need to worry about the label control creations yourself.

Upvotes: 0

Jamie Treworgy
Jamie Treworgy

Reputation: 24334

Dynamically created controls are not persisted after a postback. You need to keep track of how many controls you have generated and regenerate ALL of them each time for this to work how you want. Basic implementation:

List<string> LabeIDList = new List<string>();

override SaveViewState(..)
{
    if (LabelIDList.Count>0) {
      ViewState["LabelDIList"]=LabelIDList;
    }
    base.SaveViewState(..)
}
override LoadViewState()
{
    base.LoadViewState();
    if (ViewState["LabelIDList"]!=null) {
        LabelIDList = (List<string>)ViewState["LabelIDList"];
    }
}
override void OnLoad(..) 
{
    foreach (string id in LabelIDList)
    {
        // Make a function essentially like your code in createTaskLabel,
        // you can use it there too
        RecreateControl(id);
    }
}

private void createTaskLabel(Guid GoalID, string Goal)
{ 
    ...
    // save the ID you just created
    LabelIDList.Add(taskLabel.ID);
}

I just realized that these are Labels you're creating - so actually you should probably be keeping track of the Text instead of the ID. If the actual ID is important for some reason then keep track of them both, use a List<Tuple<string,string>> for that. More typical situation is creating input controls, though, in which case ASP.NET will persist the data that a user entered as long as you re-create them on or before OnLoad (assuming ViewState enabled).

Upvotes: 5

Related Questions