如何将ASP.NET下拉列表DataTextField属性绑定到嵌套属性

时间:2011-04-19 18:51:45

标签: asp.net binding drop-down-menu datatextfield

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

下拉数据源数据架构

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 个答案:

答案 0 :(得分:11)

假设您有一个A列表,并希望A.ID为ID字段,而ABName为Name字段,则无法直接绑定到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 };

答案 1 :(得分:0)

    cmb_category.DataSource = cc.getCat(); //source for database
    cmb_category.DataTextField = "category_name";
    cmb_category.DataValueField = "category_name";
    cmb_category.DataBind();

答案 2 :(得分:0)

以下是从类

绑定ASP.net下拉列表的2个示例

您的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;
    }
}

答案 3 :(得分:0)

您缺少所有重要的DataBind系列!

MyDropDownList.DataBind();