Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind the ASP.NET drop down list DataTextField property to a nested property

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.

Drop down data source data schema

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 behind

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

MyDropDownList.DataSource = MyList;
MyDropDownList.DataValueField = "ID";
like image 386
Michael Kniskern Avatar asked Apr 19 '11 18:04

Michael Kniskern


People also ask

What is DataTextField and DataValueField of DropDownList in asp net?

DataTextField is what the user can see. DataValueField is what you can use for identify which one is selected from DropDownList. For example you have people in your database. In this case the DataValueField can be the ID of the person and the DataTextField can be the name of the person in your DropDownList.

What is Data text field in asp net?

The DataTextField is the text that is displayed in the RadioButtonList. ASP.NET (C#) Copy.


1 Answers

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 };
like image 122
Chris Mullins Avatar answered Oct 21 '22 18:10

Chris Mullins