DataTextField in a ListBox is a combination of 2 fields

12,003

Solution 1

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.

Solution 2

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.

Share:
12,003
user29964
Author by

user29964

Updated on June 30, 2022

Comments

  • user29964
    user29964 almost 2 years

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