c# - List<MyClass> 作为 DropDownList 的数据源?

标签 c# list .net-3.5 drop-down-menu datasource

我有一个带有 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

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

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/

相关文章:

c# - 双击 ListView 中的一行

c# - 在没有焦点的 WPF TextBox 中显示光标

python - 使用 python 将字符串和 float 写入 ASCII 文件

css - 这个 CSS 到一个 SASS 列表中(类名被插入到一个属性中)?

c# - 使用 LINQ 创建增量值的 IEnumerable<>

.net-3.5 - RSACryptoServiceProvider.ImportParameters 抛出 System.Security.Cryptography.CryptographicException : Bad Data

c# - 需要将基于 C++ dll/h/lib/xml/exe 的 SDK 'wrap up' 转换为 COM 以在 C# 2.0 项目中使用

c# - 具有空列表(零计数)的 OData 结果导致错误

Python:通过为每个原始元素添加n个元素来扩展字符串列表

wpf - 在密码框中捕获返回键的最佳方法是什么? (WPF/XAML)