views:

2759

answers:

3

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

+3  A: 

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)

M4N
+3  A: 

I would recommend reading this: http://martinfowler.com/eaaDev/PresentationModel.html

Essentially you want to create a class that represents binding to a particular UI. So you would map your Model (My Object in your example) to a ViewModel object, and then bind the drop down list that way. It's a cool way to think about separation of concerns.

EDIT: Here is another blog series on ViewModel: http://blogs.msdn.com/dancre/archive/2006/10/11/datamodel-view-viewmodel-pattern-series.aspx

ecoffey
thank you, this is a useful hint for getting better architecture, but you did understand my question perfectly. :)
karlis
A: 

BTW, Try assigning the "DataTextField" and "DataValueField" before you assign the DataSource. Doing so will prevent firing the "SelectedIndexChanged" event while databinding...

Achilles