Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dropdownlist DataTextField composed from properties?

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).

like image 202
karlis Avatar asked Jan 03 '09 19:01

karlis


People also ask

What is DataValueField and DataTextField in DropDownList?

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?

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


1 Answers

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)

like image 61
M4N Avatar answered Oct 16 '22 00:10

M4N