5

我想将DataTextFieldASP.NET 下拉控件的属性绑定到作为初始数据源属性的对象的属性。我将如何完成该特定任务。

下拉数据源数据架构

public class A
{
   public string ID { get; set; }
   public B { get; set; }
} 

public class B
{
   public string Name { get; set; }  //want to bind the DataTextField to this property
}

背后的 ASP.NET 代码

DropDownList MyDropDownList = new DropDownList();
List<A> MyList = GetList();

MyDropDownList.DataSource = MyList;
MyDropDownList.DataValueField = "ID";
4

4 回答 4

12

假设您有一个 A 列表,并且希望 A.ID 是 ID 字段,ABName 是名称字段,您不能直接绑定到 B.Name,因此您要么必须在 A 上创建一个新属性才能提取从 A 的 B 属性中命名,或者您可以使用 Linq 创建一个匿名类型,为您执行此操作:

List<A> ListA = new List<A>{
    new A{ID="1",Item = new B{Name="Val1"}},
    new A{ID="2", Item =  new B{Name="Val2"}} ,          
    new A{ID="3", Item =  new B{Name="Val3"}}};

DropDownList1.DataTextField = "Name";
DropDownList1.DataValueField = "ID";
DropDownList1.DataSource = from a in ListA
                           select new { ID, Name = a.Item.Name };
于 2011-04-19T19:43:01.663 回答
0
    cmb_category.DataSource = cc.getCat(); //source for database
    cmb_category.DataTextField = "category_name";
    cmb_category.DataValueField = "category_name";
    cmb_category.DataBind();
于 2013-02-15T09:14:21.037 回答
0

这是 2 个示例,用于从类中绑定 ASP.net 中的下拉列表

你的 aspx 页面

    <asp:DropDownList ID="DropDownListJour1" runat="server">
    </asp:DropDownList>
    <br />
    <asp:DropDownList ID="DropDownListJour2" runat="server">
    </asp:DropDownList>

您的 aspx.cs 页面

    protected void Page_Load(object sender, EventArgs e)
    {
    //Exemple with value different same as text (dropdown)
    DropDownListJour1.DataSource = jour.ListSameValueText();            
    DropDownListJour1.DataBind();

    //Exemple with value different of text (dropdown)
    DropDownListJour2.DataSource = jour.ListDifferentValueText();
    DropDownListJour2.DataValueField = "Key";
    DropDownListJour2.DataTextField = "Value";
    DropDownListJour2.DataBind();     
    }

你的 jour.cs 类 (jour.cs)

public class jour
{

    public static string[] ListSameValueText()
    {
        string[] myarray = {"a","b","c","d","e"} ;
        return myarray;
    }

    public static Dictionary<int, string> ListDifferentValueText()
    {
        var joursem2 = new Dictionary<int, string>();
        joursem2.Add(1, "Lundi");
        joursem2.Add(2, "Mardi");
        joursem2.Add(3, "Mercredi");
        joursem2.Add(4, "Jeudi");
        joursem2.Add(5, "Vendredi");
        return joursem2;
    }
}
于 2013-02-23T01:44:33.440 回答
0

您缺少所有重要的 DataBind 行!

MyDropDownList.DataBind();
于 2015-06-25T09:11:32.917 回答