1

I have a List of Accounts:

List<Account> accountList;

Each Account has a ID.

I want to set all of the Accounts IDs in the accountList into a Windows-Forms ComboBox. How can I achieve that?

EDIT

Soultion using Linq:

myCombobox.DataSource = accountList.Select(x => x.ID);
baltermia
  • 1,151
  • 1
  • 11
  • 26
  • Post your `Account` definition and explain when the `Account` constructor is called, what calls it, what is `Bank`, why `Bankaccountlist` is `static` and why the `Accout` object should know about its existence. – Jimi Jun 16 '20 at 13:47
  • @Jimi `Account` and `Bank` are also different classes. I don't know why `Bankaccountlist` has to be `static`, but with all my other code only works when it's `static`. I have a `function` in `Bank` which creates an `Account`, but I define `Account` in `Account`. I shouldn't have named the `Class` and the `Constructor` the same, pretty stupid from my part. – baltermia Jun 16 '20 at 13:57
  • The class constructor needs to have the same name as the class object it builds. That's not the point. It looks like `Bank` is a Form and you're setting that collection as static to you use it in some other classes without using DataBindings or passing a reference. If `Bank.Bankaccountlist` (static or not, badly built or not) is a collection of `Account` objects, it's not possible that setting a ComboBox DataSource, you end up showing these `_012_Bank_Programm_Forms.Account` as the Item text if the Account object has an `id` property and the `DisplayMember` has been set correctly. – Jimi Jun 16 '20 at 14:09

2 Answers2

1

You can use the DataSource property as below. Here id is the propertyname which you want to display in the combobox.

toolStripComboBox1.ComboBox.DataSource = Bank.Bankaccountlist;
toolStripComboBox1.ComboBox.DisplayMember = "id";
AJITH
  • 1,145
  • 7
  • 8
  • Thanks for the help. Sadly, it doesn't work, it just shows "_012_Bank_Programm_Forms.Account". `toolStripComboBox1.ComboBox.DisplayMember = "id";`does nothing, if I comment it out, it does exactly the same. – baltermia Jun 16 '20 at 13:35
  • Did you set the display member property? Showing "_012_Bank_Programm_Forms.Account" means the item is of that type. Setting the DisplayMember should work here.If possible can share the code here? – AJITH Jun 16 '20 at 13:37
0

You can add the ID's to the Combobox with a foreach loop:

foreach (Account account in accountList) 
{
    comboboxName.Items.Add(account.id);
}

If you want the items being added at the start of the application, write the code in the constructor of your forms class:

public Form1()
{
    InitializeComponent();
    WriteIdIntoCombobox();
}

I put the foreach into the WriteIdIntoCombobox() method so that I could call it somewhere else in the code if I needed to.

baltermia
  • 1,151
  • 1
  • 11
  • 26