I need some help. I want to add an List as DataSource to a ComboBox. The List contains 1 and more elements from type "Zaehler".
I use 3 comboBoxes in my GUI. Two times it works. I create a List Element and Add Elements of T. After this I set this List as DataSource. If I check with the debugger it says that the comboBox.Items = List..Count = comboBox.DataSource.Count.
private void LadeZaehlerDaten()
{
//NEUER ZÄHLER
List<Zaehler> zaehlerArten = new List<Zaehler>();
zaehlerArten.Add(new StromZaehler(1, "Stromzähler"));
zaehlerArten.Add(new GasZaehler(2, "Gaszähler"));
cb_ZaehlerArt.DataSource = zaehlerArten;
cb_ZaehlerArt.DisplayMember = "Name";
cb_ZaehlerArt.Sorted = true;
cb_ZaehlerArt.DropDownStyle = ComboBoxStyle.DropDownList;
Zaehler z = (Zaehler)cb_ZaehlerArt.SelectedItem;
// ... more code
}
This code works correctly... I have zaehlerArten with 2 Elements and in the ComboBox I have 2 Items bzw. DataSource.Count = 2.
after this I create a new Zaehler and add this to List zaehlerList that will contains all correct Zaehler. This one goes wrong....
private void LadeVertragsDaten()
{
//NEUER VERTRAG
cb_VertragZaehler.DataSource = zaehlerList;
cb_VertragZaehler.DisplayMember = "Name"; //Property in Zaehler
cb_VertragZaehler.ValueMember = "ZaehlerNr"; //Property in Zaehler
//cb_VertragZaehler.Sorted = true;
cb_VertragZaehler.DropDownStyle = ComboBoxStyle.DropDownList;
if (cb_VertragZaehler.Items.Count < 1)
{
return;
}
else
{
Zaehler auswahl = (Zaehler)cb_VertragZaehler.SelectedItem;
}
}
If I check with the debugger ... it says das cb_VertragZaehler.Items is 0 but DataSource and zaehlerList count 2.
In my opinion I didn't do anything different. It should work the same like it does with LadeZaehlerDaten()
Since the Items of the ComboBox be 0 I can't use the information of this "Zaehler".
I did say DisplayMember is Name ... even through I did hope to use something like ZaehlerNr and Name ... booth are Properties of the class Zaehler.
Could someone say why it works in LadeZaehlerDaten() but not in LadeVertragsDaten()?
Picture: DebuggerInformation
And I really do not know why..
The list you try to assing should be immutable. Try to create a copy of it with cb_VertragZaehler.DataSource = new List<Zaehler>(zaehlerList);