0

I'm trying to loop through all the webusercontrols i have in a database and add them to a placeholder in a repeater if they exist. I can work it out, but the thing I can't work out is that I usually load a control in to a place holder like:

WebHosting ctrlWebhosting = (WebHosting)Page.LoadControl("~/Controls/" + nRow["ClientServiceList"]);

However, how do I cast to a WebHosting for example if from an item from teh database.

I thought about something like the following but it doesn't work:

DataRowView nRow = null;
switch (e.Item.ItemType)
{
    case ListItemType.Item:
    case ListItemType.AlternatingItem:
        nRow = (DataRowView)e.Item.DataItem;

        Panel PlaceHolder1 = (Panel)e.Item.FindControl("phService");
        nRow["ClientServiceList"] ctrlWebhosting = (nRow["ClientServiceList"])Page.LoadControl("~/Controls/" + nRow["ClientServiceList"]);
        ctrlWebhosting.CompanyID = Session["CompanyID"].ToString();
        PlaceHolder1.Controls.Add(ctrlWebhosting);


        break;
}

The front of the repeater is:

<asp:Repeater runat="server" ID="rptServices" OnItemDataBound="rptServices_ItemDataBound">
    <itemtemplate>
        <asp:PlaceHolder runat="server" ID="phService"></asp:PlaceHolder>
    </itemtemplate>
</asp:Repeater>
Ilya Luzyanin
  • 7,910
  • 4
  • 29
  • 49
MissCoder87
  • 2,669
  • 10
  • 47
  • 82
  • Just to clarify... are you trying to declare/cast the type of the control from a string value in the "ClientServiceList" column? – Rick Liddle Aug 07 '14 at 17:42
  • Do you really need to cast to a specific control type? Wouldn't `WebControl` suffice? – Andrei Aug 07 '14 at 17:42
  • Not sure, how would I pass the variable ctrlWebhosting.CompanyID in if I just used WebControl? – MissCoder87 Aug 07 '14 at 17:43
  • @Tom, ah, ok, missed that. Basically you cannot cast to a type which you do not know at compile time. What you could do is cast to WebControl and use reflection to set the property, or use `dynamic` – Andrei Aug 07 '14 at 17:48
  • Hmm Reflection? Got any more on that? – MissCoder87 Aug 07 '14 at 17:49
  • @Tom, here we go: [Set object property using reflection](http://stackoverflow.com/questions/619767/set-object-property-using-reflection) – Andrei Aug 07 '14 at 17:50

1 Answers1

0

reflection is your friend here, Activator.CreateInstance will let you load a type by name. I used a similar approach in a bespoke CMS years ago.

You can't assign to a property that doesn't exist so use a base class for any controls that extends a custom control rather than webcontrol.

You have your own class of controls with properties you need and can load and them to the page based on name this way.

I'm out of practice with C# but I think that will work.