Let me just preface this with: I Googled high and low for this, and found many examples and solutions, and I still can’t figure this out.
In a .aspx.cs code behind file, I have the following:
NewsArticleList listall = NewsArticleManager.GetListAll();
foreach (NewsArticle x in listall)
{
Control c1 = (NewsArticleContainer)LoadControl("~/UserControls/NewsArticleContainer.ascx");
((NewsArticleContainer)c1).PopulateWithNewsArticle(x);
mynewspanel.Controls.Add(c1);
}
I have a method in the User Control called PopulateWithNewsArticle() that accepts a NewsArticle, and populates the User Control’s web controls accordingly:
public void PopulateWithNewsArticles(NewsArticle x)
{
lbltitle.Text = x.Title;
lblcategory.Text = x.Category;
//...etc.
}
Now this works, this is fine. But what I would like to learn/understand, is how I can pass the NewsArticle x to the User Control when I LoadControl(), so that upon creation of the User Control, I can unpackage the NewsArticle on the User Control’s Page_Load, and set the web control properties from right when the User Control is instantiated as opposed to doing it after instantiation with the PopulateWithNewsArticle method (like I have it now).
Our you can expose public property
NewsArticlein theNewsArticleContainer.ascx, so you will have initialization code like this: