简体   繁体   中英

get List<CustomClass> from Page to User Control

i have a custom class List on my page code behind:

public List<Category> Categories = new List<Category>();

now, i have also a user control on that page which is supposed to display that list.

how can i access the list from the usercontrol, or, can i create a list directly in the usercontrol from the page?

my User Control codebehind:

public List<Category> Categories = new List<Category>();
protected void Page_Load(object sender, EventArgs e)
{

}

public class Category
{
    public string category_id { get; set; }
    public string category { get; set; }
}

my Page codebehind:

public List<Category> Categories = new List<Category>();
protected void Page_Load(object sender, EventArgs e)
{
    Category MyCategory = new Category();
    MyCategory.category_id = 1;
    MyCategory.category = "sample";
    Categories.Add(MyCategory);
}
public class Category
{
    public string category_id { get; set; }
    public string category { get; set; }
}

Create a property in your user control and assign the list to that property

MyUserControl.ListProperty = theList;

OR

Put the list as a public property in the page and access it via Page property in user contorl. You'll need to cast it to your page type first.

var theList = ((MyPage)Page).ListProperty

OR

Put the list in HttpContext.Current.Items and get it from there.

HttpContext.Current.Items["theList"] = theList;

since Hasan Khan has started helping me, but never answered my extra questions... i had to find my own solution.

the way i did it at the end was instead of adding items to the list on the Page, adding them directly to the user control like so:

filterControl.Categories.Add(new widgets_filter.Category{ category_id = "", category = ""});

i dont know if this is a good solution, but at least it works.

if somebody will supply a better answer ( with sample code ) , i will try and use them, meanwhile, this is what i have.

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