本文介绍了列表< MyClass>作为DropDownList的数据源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有ID和名称的简单类,我想链接到一个DropDownList,但是看来myDropDownList.DataTextField = "Name";myDropDownList.DataValueField = "ID";不可访问或不可用.

I have a simple Class with ID and Name on it which I would like to link to a DropDownList but it seems that myDropDownList.DataTextField = "Name"; and myDropDownList.DataValueField = "ID"; are not accessible or available.

更新:我正在使用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,但这对列表中每个条目的值都无济于事.

I know I could override ToString but that would not help me with the value of each entry on the list.

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

推荐答案

对于基于Web的ASP.net

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

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

用于赢奖形式

您需要指定displaymember/valuemember属性.

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

Just noticed this is a winform application try this:

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

这篇关于列表&lt; MyClass&gt;作为DropDownList的数据源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 04:31