Search code examples
c#user-controlswebforms

Setting properties on a user control inside a foreach loop


I have a user control that I use on multiple pages to show information about an object. Whenever I need to use this usercontrol, I call a method called Display (on the usercontrol) and pass in some values.

public void Display(string name, List<Items> items)
{
    // Set a few protected properties so I can display values from the aspx page
}

This works fine, but now I need to use this control inside a foreach loop in an aspx page.

<% foreach (var c in Categories) { %>
      <uc:ItemsControl runat="server"/>
<% } %>

The categories object has the methods and properties that I would otherwise pass into the Display method. So how would I properly set the values?

I tried making the properties on the user control public and just setting them in this way:

<uc:ItemsControl Items="<%# c.Items %>" 
                 OtherProperty="<%# c.GetProperty() %>" 
                 runat="server"/>

This doesn't work, because the properties getting sent in are empty. If I use <%= then it doesn't work and actually throws an error because it doesn't recognize 'c' (unless I take off runat="server" then it will at least compile, it still won't work though.

What is the proper way to do this?

Edit: Also, a repeater control might make this easier for databinding, but I'd prefer to avoid the use of any .NET controls.


Solution

  • While Justin Grant's answer would likely hav worked just fine, we decided to go with just loading the user control and calling the DisplayResults method.

    <% ((UserControlType)LoadControl("~/pathToUserControl.ascx"))
           .DisplayResults(ItemName, ItemList)); %>
    

    That is not the complete code, but it is what was needed to solve the issue I addressed in the question. By loading the user control this way, we could set the properties we needed and display the uesr control with the correct information.