1

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.

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Not a problem. Good luck with the rest of your project :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.