programing
What's the simplest way to bind a Listbox to a List of objects?
You're looking for the DataSource property:
DataSource property
List<SomeType> someList = ...; myListBox.DataSource = someList;
You should also set the DisplayMember property to the name of a property in the object that you want the listbox to display. If you don't, it will call ToString().
DisplayMember
ToString()
Pretending you are displaying a list of customer objects with "customerName" and "customerId" properties:
listBox.DataSource = customerListObject; listBox.DataTextField = "customerName"; listBox.DataValueField = "customerId"; listBox.DataBind();
Edit: I know this works in asp.net - if you are doing a winforms app, it should be pretty similar (I hope...)
Binding a System.Windows.Forms.Listbox Control to a list of objects (here of type dynamic)
List<dynamic> dynList = new List<dynamic>() { new {Id = 1, Name = "Elevator", Company="Vertical Pop" }, new {Id = 2, Name = "Stairs", Company="Fitness" } }; listBox.DataSource = dynList; listBox.DisplayMember = "Name"; listBox.ValueMember = "Id";
Granted, this isn't going to provide you anything truly meaningful unless the objects have properly overriden ToString() (or you're not really working with a generic list of objects and can bind to specific fields):
List<object> objList = new List<object>(); // Fill the list someListBox.DataSource = objList;
ListBox1.DataSource = CreateDataSource(); ListBox1.DataTextField = "FieldProperty"; ListBox1.DataValueField = "ValueProperty";
Please refer to this article for detailed examples.
There are two main routes here:
1: listBox1.DataSource = yourList;
listBox1.DataSource = yourList;
Do any manipulation (Add/Delete) to yourList and Rebind. Set DisplayMember and ValueMember to control what is shown.
2: listBox1.Items.AddRange(yourList.ToArray());
listBox1.Items.AddRange(yourList.ToArray());
(or use a for-loop to do Items.Add(...))
Items.Add(...)
You can control Display by overloading ToString() of the list objects or by implementing the listBox1.Format event.
I haven 't seen it here so i post it because for me is the best way in winforms:
List<object> objList = new List<object>(); listBox.DataSource = objList ; listBox.Refresh(); listBox.Update();
For a UWP app:
XAML
<ListBox x:Name="List" DisplayMemberPath="Source" ItemsSource="{x:Bind Results}"/>
C#
public ObservableCollection<Type> Results
ReferenceURL : https://stackoverflow.com/questions/2675067/binding-listbox-to-listobject