从类到组合框的绑定列表

时间:2018-01-11 12:31:24

标签: c# list class combobox binding

我目前正在C#中编写一个非常小的程序,并且我希望将此列表绑定到组合框。现在,我已将该列表放在一个类中,并希望将该列表绑定到组合框。下面的代码显示了我到目前为止的进展:

表格

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

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

    }
}

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

现在,我要诚实地对待你:我对课程和方法的知识和经验并不完美。这就是解决方案可能比我想象的更简单的原因。请不要对此进行评判,我还在学习!

无论如何,我希望有人能帮助我解决这个问题!

1 个答案:

答案 0 :(得分:0)

简单地

 cboxLocToevoegen.DataSource = listofLocaties ;

或直接

 cboxLocToevoegen.DataSource = locaties.retrieveLocations();

您也可以直接绑定到Locaties列表,然后选择要在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];

但是你必须写一个新的Locaties类:)