如何在ASP.NET绑定列表DataTextField属性下降到一个嵌套属性 [英] How to bind the ASP.NET drop down list DataTextField property to a nested property

查看:94
本文介绍了如何在ASP.NET绑定列表DataTextField属性下降到一个嵌套属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要一个ASP.NET的 DataTextField 属性绑定控制下降到一个对象,它是初始数据源的一个属性的属性。我将如何完成这一特定的任务。

I want to bind the DataTextField property of a ASP.NET drop down control to a property of an object that is a property of the initial data source. How would I accomplish that particular task.

下拉数据源的数据模式

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 code

DropDownList MyDropDownList = new DropDownList(); List<A> MyList = GetList(); MyDropDownList.DataSource = MyList; MyDropDownList.DataValueField = "ID";


推荐答案

说你有一个清单,并希望A.ID是ID字段,并ABName是名称字段,你不能绑定到B .NAME直接,让你无论是要创建上的一个新的属性拉出了名的A的b属性,或者你可以使用LINQ创建一个匿名类型,它会为你这样的:

Say you have a List of A, and want A.ID to be the ID field, and A.B.Name to be the Name field, you cannot bind to B.Name directly, so you either have to create a new property on A to pull the name out of the B property of A or you can use Linq to create an anonymous type that does it for you like this:

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

这篇关于如何在ASP.NET绑定列表DataTextField属性下降到一个嵌套属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆