How to associate an ASP.NET DataTextField dropdown with a nested property

I want to bind the DataTextField property of an ASP.NET control to a property of an object, which is a property of the original data source. How would I accomplish this specific task.

Data Source Data Dropdown

 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 for

 DropDownList MyDropDownList = new DropDownList(); List<A> MyList = GetList(); MyDropDownList.DataSource = MyList; MyDropDownList.DataValueField = "ID"; 
+4
source share
4 answers

Say that you have list A and want A.ID to be an ID field and ABName to be a Name field, you cannot directly contact B.Name, so you need to either create a new property on A to get the name from BA properties or you can use Linq to create an anonymous type that does this for you as follows:

 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 }; 
+11
source
  cmb_category.DataSource = cc.getCat(); //source for database cmb_category.DataTextField = "category_name"; cmb_category.DataValueField = "category_name"; cmb_category.DataBind(); 
0
source

Here are two examples for binding an ASP.net dropdown from a class

Your aspx page

  <asp:DropDownList ID="DropDownListJour1" runat="server"> </asp:DropDownList> <br /> <asp:DropDownList ID="DropDownListJour2" runat="server"> </asp:DropDownList> 

Your aspx.cs page

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

Your class 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; } } 
0
source

You are missing the whole important row of DataBind!

 MyDropDownList.DataBind(); 
0
source

All Articles