DataTextField in a ListBox is a combination of 2 fields

狂风中的少年 提交于 2019-12-06 10:44:05

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!