列表<;MyClass>;作为DropDownList的数据源

本文关键字:DropDownList 数据源 作为 MyClass lt 列表 gt | 更新日期: 2023-09-27 17:58:43

我有一个简单的class,上面有ID和Name,我想将其链接到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;

我知道我可以覆盖ToString,但这对我处理列表中每个条目的值没有帮助。

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

列表<;MyClass>;作为DropDownList的数据源

适用于基于web的ASP.net

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

MyDropDownList.DataSource = myList;
MyDropDownList.DataTextField="Name";
MyDropDownList.DataValueField="ID"; 
MyDropDownList.DataBind();

获胜形式

您需要指定displaymember/valuemember属性。

刚刚注意到这是一个winform应用程序,请尝试以下操作:

MyDropDownList.DataSource = myList;
MyDropDownList.DisplayMember = "Name";
MyDropDownList.ValueMember = "ID";