Reputation: 1135
How can I bind List to the datasource of a Listbox? I want to to set the visible property Name.
Here is my class and list:
public class Users
{
public string Name { get; set; }
public DateTime Data { get; set; }
public int Id { get; set; }
public Users()
{
Name = null;
Data = DateTime.Now;
Id = 0;
}
public Users(string N,DateTime dateTime, int id)
{
Name = N;
Data = dateTime;
Id = id;
}
}
Here is how I try to bound the datasource:
ListBox1.DataSource = ((List<Users>) Application["Users_On"]);
ListBox1.DataBind();
Upvotes: 0
Views: 7119
Reputation: 1104
Alex, not really sure how you are trying to generate and bound the values, I'll try to simplify, lets say I have a class called GenericLists
, where I'll declare all the reusable generic data, let's assume products for example so I can do like this :
private Dictionary<int, string> relatedProducts { set; get;}
public Dictionary<int, string> relatedProductsList {
get {return relatedProducts; }
}
public GenericLists()
{
relatedProducts = new Dictionary<int, string>
{
{0, "CTRL + Click to select multiples"},
{1, "A"},
{2, "B"},
{3, "C"},
{4, "D"},
};
}
And now I want to bind it to a listbox in any form :
GenericLists gList = new GenericLists();
products.DataSource = gList.relatedProductsList;
products.DataValueField = "Key";
products.DataTextField = "Value";
products.DataBind();
I hope this would give you an idea.
Good Luck
Upvotes: 0
Reputation: 8421
ListBox1.DataSource = ((List<Users>) Application["Users_On"]);
ListBox1.DataTextField = "Name";
ListBox1.DataBind();
You can use the DataTextField property of the ListBox class to display the Name propperty of your object.
Upvotes: 3