简体   繁体   中英

How to pass parameters to UserControl from Repeater in codebehind c#

I need to loop through a collection and pass the values to a UserControl. It's dynamic and I can't figure out how to pass the parameter values. I'm using a repeater.

<asp:Repeater runat="server" id="Repeater1">
  <ItemTemplate>
     <uc1:testControl ID="testControl1" runat="server"   />
  </ItemTemplate>
</asp:Repeater>

In the code behind:

Repeater1.DataSource = _myCollection;
                Repeater1.DataBind();

Any help would be greatly appreciated! Thanks

ASPX code:

<asp:Repeater runat="server" id="Repeater1" OnItemDataBound="Repeater1_ItemDataBound">
    <ItemTemplate> 
        <uc1:testControl ID="testControl1" runat="server" /> 
    </ItemTemplate > 
</asp:Repeater>

Codebehind:

protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    testControl ctrl = e.Item.FindControl("testControl1") as testControl;

    if (ctrl != null)
        ctrl.MyParameterName = "Foo";
}

you can achieve that in a much simpler manner:

<asp:DataList RepeatLayout="Table" RepeatColumns="2" RepeatDirection="Horizontal" runat="server" ID="dl">
            <ItemTemplate>              
                <uc1:UCGroup ID="UCGroup1" runat="server" Title=<%# DataBinder.Eval(Container.DataItem, "RecipientGroup.Name") %> />

                    <div class="template_over"> 
                        <a href="/ScheduleCampaign/<%# DataBinder.Eval(Container.DataItem, "RecipientGroup.Name") %>">

                      <%# DataBinder.Eval(Container.DataItem, "Email") %>

                    </a>
                    </div>
              </ItemTemplate>               
            </asp:DataList>

public partial class ChooseGroup : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        dl.DataSource = GroupsHndlr.GetExtendedRecipients(MySession.Current.ClientId);
        dl.DataBind();
    }
}

The code of the control:

<asp:Label ID="lbltitle" runat="server"></asp:Label>

<asp:Repeater ID="rpRecipients" runat="server">
   <ItemTemplate>   
       1
       </ItemTemplate>
</asp:Repeater>

public partial class UCGroup : System.Web.UI.UserControl
{
    public string Title { get; set; }
    public List<string> Recipients { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {
        this.lbltitle.Text = Title;
        this.rpRecipients.DataSource = Recipients;
        this.rpRecipients.DataBind();
    }
}

Repeater.ItemDataBound事件添加事件处理程序...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM