列出<MyClass>作为DropDownList的数据源?

Pri*_*rix 6 c# datasource list .net-3.5 drop-down-menu

我有一个带ID和名称的简单类,我想链接到DropDownList但似乎myDropDownList.DataTextField = "Name";并且myDropDownList.DataValueField = "ID";无法访问或可用.

更新:我正在使用winforms

public class Test
{
    public int ID { get; set; }
    public string Name { get; set; }
}

List<Test> myList = new List<Test>()
{
    // bla bla bla some entries bla bla bla you got the point.
};
myDropDownList.DataSource = myList;
Run Code Online (Sandbox Code Playgroud)

我知道我可以覆盖ToString,但这不会帮助我查看列表中每个条目的值.

是否有其他选项可以在下拉列表中打印名称,同时将另一个属性作为值(即:在选择值或项目作为ID时打印名称)?

Jon*_*onH 12

对于基于Web的ASP.net

您需要指定下拉列表datatextfielddatavaluefield属性.

MyDropDownList.DataSource = myList;
MyDropDownList.DataTextField="Name";
MyDropDownList.DataValueField="ID"; 
MyDropDownList.DataBind();
Run Code Online (Sandbox Code Playgroud)

对于胜利形式

您需要指定displaymember/ valuememberproperties.

刚刚注意到这是一个winform应用程序试试这个:

MyDropDownList.DataSource = myList;
MyDropDownList.DisplayMember = "Name";
MyDropDownList.ValueMember = "ID";
Run Code Online (Sandbox Code Playgroud)