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

查看:27
本文介绍了如何将 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 代码

ASP.NET code behind

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

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

推荐答案

假设你有一个 A 的 List,并希望 A.ID 为 ID 字段,ABName 为 Name 字段,你不能绑定到 B.Name 直接,因此您必须在 A 上创建一个新属性以从 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天全站免登陆