DataTextField in a ListBox is a combination of 2 fields

允我心安 提交于 2019-12-08 02:55:51

问题


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


回答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.




回答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.



来源:https://stackoverflow.com/questions/861982/datatextfield-in-a-listbox-is-a-combination-of-2-fields

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