Reputation: 9033
What's the simplest way to bind a Listbox to a List of objects in Windows Forms?
Upvotes: 65
Views: 195892
Reputation: 69
ListBox1.DataSource = CreateDataSource();
ListBox1.DataTextField = "FieldProperty";
ListBox1.DataValueField = "ValueProperty";
Please refer to this article for detailed examples.
Upvotes: 4
Reputation: 273179
There are two main routes here:
1: 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());
(or use a for-loop to do Items.Add(...)
)
You can control Display by overloading ToString() of the list objects or by implementing the listBox1.Format event.
Upvotes: 2
Reputation: 454
For a UWP app:
XAML
<ListBox x:Name="List" DisplayMemberPath="Source" ItemsSource="{x:Bind Results}"/>
C#
public ObservableCollection<Type> Results
Upvotes: -1
Reputation: 585
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();
Upvotes: 3
Reputation: 5942
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";
Upvotes: 17
Reputation: 887225
You're looking for the 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()
.
Upvotes: 76
Reputation: 21905
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...)
Upvotes: 17
Reputation: 245389
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;
Upvotes: 6