0

I'm currently writing a pretty small program in C# and have this list that I want to bind to a combobox. Now, I've put that list in a class, and want to bind that list to a combobox. The code below shows how far I've come so far:

Form

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        Locaties locaties = new Locaties();
        List<string> listofLocaties = locaties.retrieveLocations();

        cboxLocToevoegen.DataSource = ???;
        cboxLocOverzicht.DataSource = ???;

    }
}

Class

class Locaties
{
    public List<string> retrieveLocations()
    {
        List<string> LocatieList = new List<string>();
        LocatieList.Add("Koelkast");
        LocatieList.Add("Keukenlade");
        LocatieList.Add("Voorraadruimte");
        LocatieList.Add("Overige");

        return LocatieList;
    }
}

Now, I'm gonna be honest with you: my knowledge and experience with classes and methods is not perfect. That's why the solution might probably be simpler than I think. Please don't judge me on that, I'm still learning!

Anyway, I hope anyone can help me out with this!

Tom
  • 23
  • 6
  • What happens when you do `cboxLocToevoegen.DataSource = listofLocaties`? – Chetan Jan 11 '18 at 12:35
  • 1
    Possible duplicate of [how to bind a list to a combobox? (Winforms)](https://stackoverflow.com/questions/600869/how-to-bind-a-list-to-a-combobox-winforms) – Vadym Buhaiov Jan 11 '18 at 12:35
  • Alternatively you could add strings directly to the `ComboBox`es, or instances of `Locaties` itself if you provide a `ToString()` method that generates the text you want shown for each entry. – jrh Jan 11 '18 at 12:55

1 Answers1

0

Simply

 cboxLocToevoegen.DataSource = listofLocaties ;

or directly

 cboxLocToevoegen.DataSource = locaties.retrieveLocations();

you can also bind directly to a list of Locaties and then choose the property to display in the CB :

List<Locaties> listofLocaties = new List<Locaties>();
...
//Populate the list
...
cboxLocToevoegen.DataSource = listofLocaties ;
cboxLocToevoegen.DisplayMember = [a property of Locaties class];
// and the value of the CB could be another property of Locaties class:
cboxLocToevoegen.ValueMember = [the value property of Locaties class];

But ofc you have to write a new Locaties class :)