How to Bind a List to a Combobox

How to bind a List to a ComboBox?

As you are referring to a combobox, I'm assuming you don't want to use 2-way databinding (if so, look at using a BindingList)

public class Country
{
public string Name { get; set; }
public IList<City> Cities { get; set; }
public Country(string _name)
{
Cities = new List<City>();
Name = _name;
}
}



List<Country> countries = new List<Country> { new Country("UK"), 
new Country("Australia"),
new Country("France") };

var bindingSource1 = new BindingSource();
bindingSource1.DataSource = countries;

comboBox1.DataSource = bindingSource1.DataSource;

comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Name";

To find the country selected in the bound combobox, you would do something like: Country country = (Country)comboBox1.SelectedItem;.

If you want the ComboBox to dynamically update you'll need to make sure that the data structure that you have set as the DataSource implements IBindingList; one such structure is BindingList<T>.


Tip: make sure that you are binding the DisplayMember to a Property on the class and not a public field. If you class uses public string Name { get; set; } it will work but if it uses public string Name; it will not be able to access the value and instead will display the object type for each line in the combo box.

Bind List to comboBox in C#

I found the problem. The problem is that I'm an idiot sometimes:

private void cargarCombo<T>(ComboBox combo, List<T> data, string displayMember, string valueMember)
{
BindingSource source = new BindingSource();
source.DataSource = data;

combo.DataSource = source.DataSource;
cmbEstadoAsistencia.DisplayMember = displayMember;
cmbEstadoAsistencia.ValueMember = valueMember;
}

cmbEstadoAsistencia should be change to combo

I was hardcoding the name of one of the comboBoxes.
I'm sorry for posting garbage :(

Binding a generic List string to a ComboBox

You need to call the Bind method:

cbxProjectd.DataBind();

If this is for winforms then you need to make sure what you have is being called, the following works:

BindingSource bs = new BindingSource();
bs.DataSource = new List<string> { "test1", "test2" };
comboBox1.DataSource = bs;

Although you can set the ComboBox's DataSource directly with the list.

WPF Combobox binding with List string

<Combobox ItemsSource="{Binding Property}" SelectedItem="{Binding SimpleStringProperty, Mode=TwoWay}" Text="Select Option" />

That's untested, but it should at least be pretty close to what you need.

Bind a List string to a combobox

You can popuplate a ComboBox, in fact every ItemsControl, in 2 Ways.

First: Add directly Items to it, which works in Code or in Xaml

<ComboBox>
<ComboBoxItem Name="Item1" />
<ComboBoxItem Name="Item2" />
</ComboBox>

but this is rather static.
The second approach uses a dynamic list.

As an example, lets assume you have a window and a combobox in your xaml. The Combobox gets x:Name="myCombobox"

In your code behind you can create your List and set it as an ItemsSource

List<string> myItemsCollection = new List<string>();
public Window1()
{
InitializeComponent();
myItemsCollection.Add("Item1");
myCombobox.ItemsSource = myItemsCollection;
}

this works fine, but has one problem. If you change the List after you set it as an ItemsSource, the UI will not catch up with the newest change. So to make that work aswell, you need to use an ObservableCollection now the collection can notify any changes, which the UI will listen to. and automatically add the new item to the combobox.

WPF: Binding a List class to a ComboBox

Here a simple example using the MVVM Pattern

XAML

<Window x:Class="Binding_a_List_to_a_ComboBox.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid HorizontalAlignment="Left"
VerticalAlignment="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="25"/>
</Grid.RowDefinitions>

<ComboBox Grid.Column="0" Grid.Row="0" ItemsSource="{Binding SearchPointCollection , UpdateSourceTrigger=PropertyChanged}"
SelectedIndex="{Binding MySelectedIndex, UpdateSourceTrigger=PropertyChanged}"
SelectedItem="{Binding MySelectedItem, UpdateSourceTrigger=PropertyChanged}">
<ComboBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Text="{Binding Id}" Grid.Row="0"/>
<TextBlock Text="{Binding Name}" Grid.Row="1"/>
<TextBlock Text="{Binding Otherstuff}" Grid.Row="2"/>
</Grid>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<Button Content="Bind NOW" Grid.Column="0" Grid.Row="1" Click="Button_Click"/>
<TextBlock Text="{Binding MySelectedIndex, UpdateSourceTrigger=PropertyChanged}" Grid.Column="1" Grid.Row="0"/>

<Grid Grid.Column="1" Grid.Row="1"
DataContext="{Binding MySelectedItem, UpdateSourceTrigger=PropertyChanged}">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>

<TextBlock Text="{Binding Id}" Grid.Column="0"/>
<TextBlock Text="{Binding Name}" Grid.Column="1"/>
<TextBlock Text="{Binding SomeValue}" Grid.Column="2"/>
</Grid>
</Grid>

Code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using Import_Rates_Manager;

namespace Binding_a_List_to_a_ComboBox
{
/// <summary>
/// Interaktionslogik für MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
DataContext = new coImportReader();
}
}
}
namespace Import_Rates_Manager
{
public class coImportReader : INotifyPropertyChanged
{
private List<coSearchPoint> myItemsSource;
private int mySelectedIndex;
private coSearchPoint mySelectedItem;

public List<coSearchPoint> SearchPointCollection
{
get { return myItemsSource; }
set
{
myItemsSource = value;
OnPropertyChanged("SearchPointCollection ");
}
}

public int MySelectedIndex
{
get { return mySelectedIndex; }
set
{
mySelectedIndex = value;
OnPropertyChanged("MySelectedIndex");
}
}

public coSearchPoint MySelectedItem
{
get { return mySelectedItem; }
set { mySelectedItem = value;
OnPropertyChanged("MySelectedItem");
}
}

#region cTor

public coImportReader()
{
myItemsSource = new List<coSearchPoint>();
myItemsSource.Add(new coSearchPoint { Name = "Name1" });
myItemsSource.Add(new coSearchPoint { Name = "Name2" });
myItemsSource.Add(new coSearchPoint { Name = "Name3" });
myItemsSource.Add(new coSearchPoint { Name = "Name4" });
myItemsSource.Add(new coSearchPoint { Name = "Name5" });
}
#endregion

#region INotifyPropertyChanged Member

public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}

#endregion
}

public class coSearchPoint
{
public Guid Id { get; set; }
public String Name { get; set; }
public IRange FoundCell { get; set; }

public coSearchPoint()
{
Name = "";
Id = Guid.NewGuid();
FoundCell = null;
}
}

public interface IRange
{
string SomeValue { get; }
}
}

Here are 3 Classes:

  • MainWindow which set VM as his Datacontext
  • coImportReader the Class which presents your properties for your bindings
  • coSearchPoint which is just a Container for your information
  • IRange which is just an Interface


Related Topics



Leave a reply



Submit