我有一个带有 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;
我知道我可以重写 ToString 但这对列表中每个条目的值没有帮助。
是否有任何其他选项可以在将另一个属性作为值的同时在下拉列表上打印名称(即:在将所选值或项目作为 ID 的同时打印名称)?
最佳答案
基于 web 的 ASP.net
您需要指定下拉列表 datatextfield
和 datavaluefield
属性。
MyDropDownList.DataSource = myList;
MyDropDownList.DataTextField="Name";
MyDropDownList.DataValueField="ID";
MyDropDownList.DataBind();
对于胜利形式
您需要指定 displaymember
/valuemember
属性。
刚刚注意到这是一个 winform 应用程序试试这个:
MyDropDownList.DataSource = myList;
MyDropDownList.DisplayMember = "Name";
MyDropDownList.ValueMember = "ID";
关于c# - List<MyClass> 作为 DropDownList 的数据源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6296611/