views:

435

answers:

2

I have a user control with property (*.acsx.cs):

public partial class controls_PersonAccessStatus : System.Web.UI.UserControl
{
    public Person Person { get; set; }   
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

Is there some way to pass parameter to this control in *.aspx, something like this

<%  foreach (Person p in persons) {  %>
        <uc:PersonAccessStatus ID="PersonAccessStatus" runat="server" Person=p />
<%  } %>
+3  A: 

Yes. You can create a property on the UserControl. I typically use it to enable or disable functions of a control. It is simple to assign a value in the aspx.

<uc:PersonAccessStatus ID="PersonAccessStatus" runat="server" EnableSomething="true" />

I am not sure about the syntax for your example as I usually keep code out of the aspx, so I would do the looping in the code.

foreach (Person p in persons)
{
    control = LoadControl("~/App_Controls/PersonAccessStatus.ascx") 
        as PersonAccessStatus;

    control.Person = p;

    SomeContainer.Controls.Add(control);
}
g .
A: 

Thank you g. You really helped me although I have not found more elegant solution. From *.aspx side it looks so:

<%foreach (Person p in persons) 
  {          
    controls_PersonAccessStatus control = LoadControl("~/App_Controls/PersonAccessStatus.ascx") as controls_PersonAccessStatus;
    control.Person = p;  %>
    <%=RenderControl(control) %>      
<%}%>

Where RenderControl ia a helper function:

public string RenderControl(Control ctrl)
{
    StringBuilder sb = new StringBuilder();
    StringWriter tw = new StringWriter(sb);
    HtmlTextWriter hw = new HtmlTextWriter(tw);

    ctrl.RenderControl(hw);
    return sb.ToString();
}