How to add controls to usercontrol at runtime?

dotnetman

Newcomer
Joined
Jan 4, 2005
Messages
19
Friends,
I need your help real bad :( I have a user control that I have created which displays a bunch of labels (via a method). Now I am using this usercontrol in my form and I have a method in the container form that basically needs to set the number of labels this usercontrol shows. Now the method within the user control adds the labels properly the first time around. Next time, if I need to re-render the updated user control with a set of new labels, how do I do it?

Pls throw some light.

Thank you,
DNM
 
Can you use a boolean to do it. First time through it is false and in an if statement if false show these and hide the others. Next time certain condition is met so set it true and in the if statement else show these and hide those.

tk
 
You need to manipulate the Controls[] collection of the user control that renders the labels either from the container Form or within the user control itself.

Code:
// Method in container Form
public void AddChildLabels(int lblCount)
{
    // Clear out existing Labels
    this.childCtrl.Controls.Clear();
    
    // Add new Labels
    for(int count = 1; count <= lblCount; count++)
    {
        Label lbl = new Label();
        this.childCtrl.Controls.Add(lbl);
        // Set any properties of the Label - e.g. Location, Size, Text, etc.
    }
}

You will obviously have to make your code more sophisticated than what I have laid out if your user control contains Controls that you don't want to trash or to grab the required properties for the Label......but I think this answers your question.
 
RobEmDee said:
You need to manipulate the Controls[] collection of the user control that renders the labels either from the container Form or within the user control itself.

Code:
// Method in container Form
public void AddChildLabels(int lblCount)
{
    // Clear out existing Labels
    this.childCtrl.Controls.Clear();
    
    // Add new Labels
    for(int count = 1; count <= lblCount; count++)
    {
        Label lbl = new Label();
        this.childCtrl.Controls.Add(lbl);
        // Set any properties of the Label - e.g. Location, Size, Text, etc.
    }
}

You will obviously have to make your code more sophisticated than what I have laid out if your user control contains Controls that you don't want to trash or to grab the required properties for the Label......but I think this answers your question.


Thanx a lot RobEmDee. Your suggestion worked. This is why I love this forum. :cool:
 
Back
Top