User Control Inside Repeater

前端 未结 2 1610
悲哀的现实
悲哀的现实 2020-12-29 08:13

I have a UserControl inside a repeater. The repeater\'s datasource is from SQL Server.

User Control\'s .cs - MoviePanel.ascx.cs:


public int m         


        
2条回答
  •  [愿得一人]
    2020-12-29 08:47

    here is one way, doing it all in the code behind. I can't say this is best practice, but it's clean. You use the ItemDataBind event, cast the item to what you want, datatable, whatever, then create a new instance of the user control and add it to the repeater's control collection

    Page source

    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var myList = new List() { "one", "two", "three" };
            myRepeater.DataSource = myList;
            myRepeater.DataBind();
        }
    
        public void R1_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
        {
            var items = (string)e.Item.DataItem;
            var newcontrol = (WebUserControl1)Page.LoadControl("~/WebUserControl1.ascx");
            newcontrol.myTest = items;
            myRepeater.Controls.Add(newcontrol);           
        }   
    }
    

    Page html

     
        
    
        
    
    

    user control

    and

    public partial class WebUserControl1 : System.Web.UI.UserControl
    {
        public string myTest { get; set; }
        protected void Page_Load(object sender, EventArgs e)
        {
            myLabel.InnerText = myTest;
        }
    }
    

提交回复
热议问题