views:

1026

answers:

2

I have a listbox containing Users. The datasource is an generic list of the type User (contains, id, firstname, lastname, ...). Now I want to use the id as datavalue (through dataValueField) and I want LastName + ' ' + Firstname as a DataTextField.

Can anyone tell me how this is possible?

I'm using C# (ASP.NET).

+4  A: 

The easiest way is to add a new property to the User class that contains the full name:

public string FullName
{
    get { return LastName + " " + FirstName; }
}

And bind the listbox to that.

This has the advantage of centralising the logic behind how the full name is constructed, so you can use it in multiple places across your website and if you need to change it (to Firstname + " " + Lastname for example) you only need to do that in one place.

If changing the class isn't an option you can either create a wrapper class:

public class UserPresenter
{
    private User _user;

    public int Id
    {
        get { return _user.Id; }
    }

    public string FullName
    {
        get { return _user.LastName + " " + _user.Firstname; }
    }
}

Or hook into the itemdatabound event (possibly got the name wrong there) and alter the list box item directly.

Martin Harris
I think I'll have to do it like this then. I really was hoping there was an other option. Thx buddy
Sem Dendoncker
A: 
list.DataTextField = string.Format("{0}, {1}", LastName, Firstname);

If you use it elsewhere you could also add a DisplayName property to the User class that returns the same thing.

Christian Hagelid
Won't that just set the listbox to look for a property called the combination of whatever LastName and FirstName variables are in scope when you run this line? I haven't really used asp.net since version 2.0, so if this is a new feature I'd be interested to see an example of where exactly you'd add this line of code - I don't see how it could work in the page constructor for example...
Martin Harris