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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/861982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 04:39:24  来源:igfitidea点击:

DataTextField in a ListBox is a combination of 2 fields

c#asp.netlistboxdatasourcedatatextfield

提问by user29964

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.

我有一个包含用户的列表框。数据源是用户类型的通用列表(包含、id、名字、姓氏、...)。现在我想使用 id 作为数据值(通过 dataValueField),我想要 LastName + ' ' + Firstname 作为 DataTextField。

Can anyone tell me how this is possible?

谁能告诉我这怎么可能?

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

我正在使用 C# (ASP.NET)。

采纳答案by Martin Harris

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 事件(可能在那里弄​​错了名称)并直接更改列表框项目。

回答by Christian Hagelid

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.

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