Search code examples
c#winformscomboboxtoolstrip

Set Windows-Forms ComboSox DataSource to specific attributes of objects in a List


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);

Solution

  • 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.