views:

448

answers:

2

I have a usercontrol that contains a datalist, and I want to set the datasource of the datalist to different things depending on what page the usercontrol is on.

So, I think what I need to do is expose a public property of the datalist that will get the datasource and set it, like so:

public datasource UserDataSource
{
get { return DataList1.DataSource; }
set { DataList1.DataSource = value; }
}

but the above obviously doesn't work. I'd then call it like this:

MyUserControl.UserDataSource = datasourcename;

and then somehow databind the datalist inside the usercontrol.

Obviously I'm kind of out of my element here, but hopefully I can get this working. Thanks for any help.

+1  A: 

You need to use find control method to find your datalist first and then assign datasource like...

DataList dl = (DataList)yourLoadedusercontrol.FindControl("yourDatalist");
    dl.DataSource = yourdatasource;
Muhammad Akhtar
This worked perfectly. Thank you.
somacore
+1  A: 

I know you have already accepted an answer, but I feel I must add my thoughts:

Your original idea was correct - you just needed to call the databind method of your datalist after setting the datasource. I truly do not feel that doing the above mentioned method is the best way. You should really just have a method or writeonly property (like you do) that takes a possible IList or IEnumerable of your custom object and binds it directly to your datalist. Your page or control that contains this user control should not be aware of your type of data control. If you change it from a Datalist to a Repeater or a GridView, you have to change it everywhere you bind to your user control.

Example:

IList<CustomClass> results = new List<CustomClass>(); //you would load your collection from your database
this.myUserControl.LoadData(results);

In your user control:

public void LoadData(IList<CustomClass> data){
  this.datalist1.datasource = data;
  this.datalist1.databind();
}
Dan Appleyard