is there a way to make the datatextfield property of a dropdownlist in asp.net via c# composed of more than one property of an object?
public class MyObject
{
public int Id { get; set; }
public string Name { get; set; }
public string FunkyValue { get; set; }
public int Zip { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
List<MyObject> myList = getObjects();
ddList.DataSource = myList;
ddList.DataValueField = "Id";
ddList.DataTextField = "Name";
ddList.DataBind();
}
I want e.g. not use "Name", but "Name (Zip)" eg.
Sure, i can change the MyObject Class, but i don't want to do this (because the MyObject Class is in a model class and should not do something what i need in the UI).
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.
The DataTextField is the text that is displayed in the RadioButtonList. ASP.NET (C#) Copy.
Add another property to the MyObject class and bind to that property :
public string DisplayValue
{
get { return string.Format("{0} ({1})", Name, Zip); }
}
Or if you can not modify MyObject, create a wrapper object in the presentation layer (just for displaying). This can also be done using some LINQ:
List<MyObject> myList = getObjects();
ddList.DataSource = (from obj in myList
select new
{
Id = obj.Id,
Name = string.Format("{0} ({1})", obj.Name, obj.Zip)
}).ToList();
ddList.DataValueField = "Id";
ddList.DataTextField = "Name";
ddList.DataBind();
(sorry I don't have Visual Studio available, so there might be errors in the code)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With