如何将ASP.NET下拉列表控件的DataTextField属性绑定到嵌套属性上。

5

我想将 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";

如果列表中有多个B,应该使用哪个B来获取Name属性? - 300 baud
@300波特率 - 我已经更新了问题,并提供了正确的情境。 - Michael Kniskern
@Michael - 在您的情况下,您直接绑定了一个B列表,并且A(包含您想要绑定的ID)不可见。 - 300 baud
@300波特 - 我已经修复了源代码中的错误。 - Michael Kniskern
@Michael - 例如,如果GetList返回一个包含5个A的列表,并且这5个A中的每个都包含一个包含5个B的列表,您希望您的DropDownList有5个项目(每个A一个)还是25个项目(每个A中的每个B一个)? - 300 baud
@Michael - 看起来你把List<B>改成了B(上次编辑时没有注意到)。在这种情况下,你可能想看看Chris Mullins的答案。 - 300 baud
4个回答

12

假设你有一个A类型的列表,想让A.ID成为ID字段,A.B.Name成为Name字段,由于无法直接绑定到B.Name,所以你需要在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 };

0

你漏掉了非常重要的DataBind代码行!

MyDropDownList.DataBind();

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

0

以下是两个在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;
    }
}

那个例子实际上并没有解决原帖提出的问题。 - Andrew Barber

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接