简体   繁体   English

ListBox中的DataTextField是2个字段的组合

[英]DataTextField in a ListBox is a combination of 2 fields

I have a listbox containing Users. 我有一个包含用户的列表框。 The datasource is an generic list of the type User (contains, id, firstname, lastname, ...). 数据源是User(包含,id,firstname,lastname,...)类型的通用列表。 Now I want to use the id as datavalue (through dataValueField) and I want LastName + ' ' + Firstname as a DataTextField. 现在我想使用id作为datavalue(通过dataValueField),我希望LastName +''+ Firstname作为DataTextField。

Can anyone tell me how this is possible? 谁能告诉我这是怎么回事?

I'm using C# (ASP.NET). 我正在使用C#(ASP.NET)。

The easiest way is to add a new property to the User class that contains the full name: 最简单的方法是向包含全名的User类添加一个新属性:

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. 或挂钩到itemdatabound事件(可能在那里名称错误)并直接更改列表框项目。

list.DataTextField = string.Format("{0}, {1}", LastName, Firstname);

如果您在其他地方使用它,您还可以向返回相同内容的User类添加DisplayName属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM