What's the simplest way to bind a Listbox to a List of objects in Windows Forms?
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().
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";
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...)
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.
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();
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.
For a UWP app:
XAML
<ListBox x:Name="List" DisplayMemberPath="Source" ItemsSource="{x:Bind Results}"/>
C#
public ObservableCollection<Type> Results
Related
Is it possible to bind a ListBox to a DataSource of List<A>, while setting the DisplayMember to a custom string composed of A's properties, such as the following $"{A.b} {A.c}"?
var list1 = new List<A>();
// populate list
MyListBox.DisplayMember = $"{A.b} {A.c}"; // not going to work
MyListBox.DataSource = list1;
I know I can use an anonymous type, but I want the ListBox.Items to remain of type A. I don't want to do the following,
var list2 = (from a in list1
select new {A = a, DisplayMember = $"{a.b} {a.c}"}).ToList();
MyListBox.DisplayMember = "DisplayMember";
MyListBox.DataSource = list2;
because now MyListBox.Items is anonymous and A can't be retrieved like var list = MyListBox.Items.OfType<A>().
So, is there any way to do that?
I was thinking about it wrong. Solved it now. Maybe it was obvious to some, but I'm going to post my answer for posterity.
Use the anonymous type in the second example, and just set the ValueMember to A
var list2 = (from a in list1
select new {A = a, DisplayMember = $"{a.b} {a.c}"}).ToList();
MyListBox.DisplayMember = "DisplayMember";
MyListBox.ValueMember = "A";
MyListBox.DataSource = list2;
var list3 = MyListBox.Items.OfType<A>().ToList(); // works!
I have a System.Windows.Forms.Listbox and a collection of tuple type values I've created. That is, the new tuple type introduced in C# 7.0. I'm trying to bind the collection to the Listbox and set the DisplayMember to one of the elements in the tuple. Here's an example:
var l = new List<(string name, int ID)>()
{
("Bob", 1),
("Mary", 2),
("Beth", 3)
};
listBox1.DataSource = l;
listBox1.DisplayMember = "name";
That doesn't work, though. With the older-style Tuple<T> you could supposedly do what's described in this answer:
listBox1.DisplayMember = "Item1";
listBox1.ValueMember = "Item3"; // optional
That doesn't work either. Here's what I'm seeing in both cases:
How can I accomplish this?
Unfortunately C#7 value tuples cannot be used for data binding because they use fields, while Windows Forms standard data binding works only with properties.
Ivan's answer, definitely describes the case. As a workaround you can use Format event of ListBox to show name filed:
private void listBox1_Format(object sender, ListControlConvertEventArgs e)
{
e.Value = (((string name, int ID))e.ListItem).name;
}
This may be a very simple question but I realized I could not get it work.
I have a Winform combo box with datasource as a List<int>
combo.DataSource = intList;
What do I put for .DisplayMember and .ValueMember in order to simply have a list of integer values? Not setting them will display nothing.
I have worked with other List<myObj> in which DisplayMember and ValueMember are myObj's properties. How about simple data type like int, string?
When retrieving the selected item, one could simply cast (int)(combo.SelectedItem) or have to go through the property corresponding to ValueMember?
The problem does not occur because you have a list of integers, it probably occurs because you add items to the list after assigning it to the .DataSource property. List does not have a mechanism to notify its container when items are added to or removed from it.
Either add items to the list before assigning it to the .DataSource property, or use a wrapper like BindingSource as Krishnraj Rana suggested.
Here BindingSource comes into picture. You can use it like this.
BindingSource bSource = new BindingSource();
bSource.DataSource = new List<int> { 1, 2, 3 };
combo.DataSource = bSource;
Though you can set datasource of combobox directly with list. like this -
combo.DataSource = intList;
This also works perfectly fine.
You can add items from list using foreach like this.
foreach (var v in intList)
{
comboBox1.Items.Add(v.ToString());
}
I have a combobox and I see that I am not able to set SelectedValue like this:
cmbA.SelectedValue = "asd"
So I tried to do this
cmbA.SelectedIndex = cmbA.FindString("asd");
Based on How to set selected value from Combobox?
I realised that my combobox is a System.Windows.Controls.ComboBox and not a System.Windows.Forms.ComboBox.
That means that FindString() is not available.
Based on User Control vs. Windows Form I get that forms are the container for controls, but I dont get why the Controls.ComboBox does not implement FindString().
Do I have to write my own code to do what FindString() does for Forms.ComboBox?
WPF ComboBoxes are not the same as WinForms ones. They can display a collection of objects, instead of just strings.
Lets say for example if I had
myComboBox.ItemsSource = new List<string> { "One", "Two", "Three" };
I could just use the following line of code to set the SelectedItem
myComboBox.SelectedItem = "Two";
We're not limited to just strings here. I could also say I want to bind my ComboBox to a List<MyCustomClass>, and I want to set the ComboBox.SelectedItem to a MyCustomClass object.
For example,
List<MyCustomClass> data = new List<MyCustomClass>
{
new MyCustomClass() { Id = 1, Name = "One" },
new MyCustomClass() { Id = 2, Name = "Two" },
new MyCustomClass() { Id = 3, Name = "Three" }
};
myComboBox.ItemsSource = data;
myComboBox.SelectedItem = data[0];
I could also tell WPF I want to consider the Id property on MyCustomClass to be the identifying property, and I want to set MyCombbox.SelectedValue = 2, and it will know to find the MyCustomClass object with the .Id property of 2, and set it as selected.
myComboBox.SelectedValuePath = "Id";
myComboBox.SelectedValue = 2;
I could even set the Display Text to use a different property using
myComboBox.DisplayMemberPath = "Name";
To summarize, WPF ComboBoxes work with more than just Strings, and because of the expanded capabilities, FindString is not needed. What you are most likely looking for is to set the SelectedItem to one of the objects that exist in your ItemsSource collection.
And if you're not using ItemsSource, then a standard for-each loop should work too
foreach(ComboBoxItem item in myComboBox.Items)
{
if (item.Content == valueToFind)
myComboBox.SelectedItem = item;
}
I don't know what you are trying to do but I think it would be easier to just do
cmbA.Text = "String";
That way you get your selected item
Else I found an intersting article that could help you out:
Difference between SelectedItem, SelectedValue and SelectedValuePath
After much searching I have still not found a solution to this.
I have created a list in VS 2010 and bound it to a ComboBox. The DataSource property shows the entire list but the combobox on the form is empty, as is the items property of the box.
private List<string> classes = new List<string>();
private BindingList<string> bindingClasses;
classes.Add("Spinning");
classes.Add("Step");
classes.Add("Pilates");
classes.Add("Kickboxing");
classes.Add("Body Sculpting");
bindingClasses = new BindingList<string>(classes);
classesComboBox.DataSource = bindingClasses;
I have also tried adding
classesComboBox.DisplayMember = "Spinning";
and without the bindingList between to no avail.
Why is this not working?
Lose the BindingList, just set the DataSource to the List<String> itself.
List<string> classes = new List<string>();
classes.Add("Spinning");
classes.Add("Step");
classes.Add("Pilates");
classes.Add("Kickboxing");
classes.Add("Body Sculpting");
classesComboBox.DataSource = classes;
classesComboBox.SelectedItem = "Spinning";
classesComboBox.DataBind();
You need to specify when it should grab the data.