Search code examples
c#asp.netwebformswebusercontrol

Using multiple same usercontrol in one webform by a loop in ASP.Net


I have a usercontrol and I want to create some instance by a loop in my web form. Everything is OK, but all of instances show same data (Data of last instance)!

My code is: (My usercontrol is: WebUserControl)

    MyDataSet.tblMyDataTable oTable = new MyDataSet.tblMyDataTable();
    MyDataSetTableAdapters.tblMyTableAdapter oAdapter
        = new MyDataSetTableAdapters.tblMyTableAdapter();
    oAdapter.Fill(oTable);
    for (int i = 0; i < oTable .Count; i++)
    {
        Context.Items["ID"] = oTable[i].ID;
        WebUserControl newControl = new WebUserControl();
        newControl = (WebUserControl)LoadControl("~/WebUserControl.ascx");
        newControl.ID = "myControl" + i.ToString();
        System.Web.UI.HtmlControls.HtmlTableRow newRow
            = new System.Web.UI.HtmlControls.HtmlTableRow();
        System.Web.UI.HtmlControls.HtmlTableCell newCell
            = new System.Web.UI.HtmlControls.HtmlTableCell();
        newCell.Controls.Add(newControl);
        newRow.Controls.Add(newCell);
        myTable.Rows.Insert(0, newRow);
    }

In the event of Page_Load in my uercontrol, my code is:

    myID = (string)Context.Items["ID"].ToString().Clone();
    ShowNewsSummary(myID);

That ShowNewsSummary is a function that fills fields of usercontrol.

Thanks.


Solution

  • You're overwriting this Context item on each iteration of the loop, meaning that only the last iteration will remain...

    Context.Items["ID"] = oTable[i].ID;
    

    The Page_Load of all user controls will only be fired after the parent page 'Page_Load` has completed.

    So you need to use the index or ID to store the value...

    newControl.ID = "myControl" + i.ToString();
    Context.Items[newControl.ID] = oTable[i].ID;
    

    And then get the value in the user control...

    myID = (string)Context.Items[this.ID].ToString().Clone();