Dynamically add WebUser Controls in a loop

2k Views Asked by At

hi I like to add Dynamically add WebUser Controls in a loop

like this con1 con2 con3 and more or less depending on the loop

is there a good way to do this

my first try look like this. but i don't know how to tell it to use the next one grpCon2

        foreach (DataRow Group in AllGroups.Rows)
    {
        GroupListControl grpCon1 = new GroupListControl();
        grpCon1.NickName = "STUFF";
        grpCon1.GroupName = "HARD";

        LiteralAddCOntrols.Text = @"<uc1:GroupListControl ID=""GrpCOn1"" runat=""server"" />";

    }
3

There are 3 best solutions below

0
On BEST ANSWER

You need to use loadcontrol(pathtoyourusercontrol), and then and the control back to your page at the location you want.

sharedUC uc = (sharedUC)LoadControl("~/sharedUC/control.ascx");
plcContent.Controls.Add(uc);

Add :

To the page aspx loading the control and you will be able to use a typed reference to it.

0
On

You can do that, but you have to remember two things:

  1. You have to give them ID - and remember them in a Session
  2. When the controls do any PostBack actions (like Click) - you have to refresh the exact collection on every post back in Page_PreInit event (which normaly the framework does) - because the attached event won't fire. And the Page_PreInit have to refresh the exact collection with the same ID-s.

It's possible but it's not so simple at the beginning.

And here is a detailed description how to do that.

https://web.archive.org/web/20211031102347/https://aspnet.4guysfromrolla.com/articles/092904-1.aspx

0
On

You can use this way and use "updatePanel" to dynamically change your controllers:

here I use "userControls_DeviceController" as my Usercontroller Class name.

userControls_DeviceController FAN1;
userControls_DeviceController FAN2;

protected void Page_Load(object sender, EventArgs e)
{
   FAN1 = (userControls_DeviceController)LoadControl("~/userControls/DeviceController.ascx");
   saloon.Controls.Add(FAN1);

   FAN2 = (userControls_DeviceController)LoadControl("~/userControls/DeviceController.ascx");
   saloon.Controls.Add(FAN2);
}

and also for customizing your usercontrol you can put a timer on your page and use an updatepanel to change properties of the specify usercontrol.

protected void Timer1_Tick(object sender, EventArgs e)
{
    int counter = Convert.ToInt32(Session["c"]);
    FAN1.SetDeviceIndex(counter);//here I change usercontrol picture FAN1
    FAN2.SetDeviceIndex(counter);//here I change usercontrol picture FAN2
    counter++;
    if (counter == 4)//I have 4 picture to changing.
    {
       counter = 0;
    }
    Session["c"] = counter;
    UpdatePanel1.Update();
}

I hope it could help you ...