我试图获取一个ListBox来显示表Accommodation的多行的串联。

因为我无法编辑数据源,所以我准备了一个类AccommodationEntity,它包含原始Accommodation对象和希望ListBox显示的字符串。

但是,由于某些原因,我无法设置ListBox的DisplayMember属性,因此无法显示默认的jibber-jabber。

我将列表框设置如下:

accommodationList.DisplayMember = "textToShow";
// load and set up accommodation
List<AccommodationEntity> relatedAccommodations =
    dt.listHolidayAccommodation(relatedHoliday);
accommodationList.DataSource = relatedAccommodations;
accommodationList.Refresh();

数据源中存储的对象的类如下所示:
class AccommodationEntity
{
    public accommodation classicAccommodation;
    public string textToShow;

    public AccommodationEntity(stay relatedStay)
    {
        this.classicAccommodation = relatedStay.accommodation;

        string from = relatedStay.dateFrom.ToString();
        string to = relatedStay.dateTo.ToString();
        string city = relatedStay.accommodation.location.ToString();
        string hotelName = relatedStay.accommodation.name.ToString();

        this.textToShow = hotelName + ", " + city + " (" + from + " - " + to + ")";
    }
}

}
`

最后,有一种方法可以进行一些搜索(返回正确的对象):
public List<AccommodationEntity> listHolidayAccommodation(holiday selectedHoliday)
{
    List<AccommodationEntity> ubytovani = new List<AccommodationEntity>();

    var stays = from singleStay in selectedHoliday.stays
                select singleStay;

    foreach (stay singleStay in stays)
    {
        AccommodationEntity newStay = new AccommodationEntity(singleStay);
        ubytovani.Add(newStay);
    }

    return ubytovani;
}

我知道dataSource包含正确的数据,但是由于某些原因,似乎DisplayMember属性仍然设置为""

任何帮助,将不胜感激。

谢谢。

最佳答案

您是否尝试过像这样设置DisplayMember和DisplayValue。其中“名称”/“值”是Accomodation类中属性的名称。

List<AccommodationEntity> relatedAccommodations = dt.listHolidayAccommodation(relatedHoliday);
accommodationList.DataSource = relatedAccommodations;
accommodationList.DisplayMember = "Name";
accommodationList.ValueMember = "Value";

更新:

确保textToShow实际上是一个Property,而不仅仅是一个公共(public)字段。

关于c# - 使用特殊类的多个DisplayMember,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8851398/

10-08 21:14