我试图让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属性似乎仍然设置为""
。
任何帮助都将不胜感激。
感谢。
答案 0 :(得分:4)
您是否设置了DisplayMember和ValueMember属性?查看MSDN上的DataSource属性,了解它们如何设置所有三个属性。
<强>更新强>
尝试切换:
accommodationList.DisplayMember = "textToShow";
// load and set up accommodation
List<AccommodationEntity> relatedAccommodations =
dt.listHolidayAccommodation(relatedHoliday);
accommodationList.DataSource = relatedAccommodations;
到此:
// load and set up accommodation
List<AccommodationEntity> relatedAccommodations =
dt.listHolidayAccommodation(relatedHoliday);
accommodationList.DataSource = relatedAccommodations;
accommodationList.DisplayMember = "textToShow";
答案 1 :(得分:3)
您是否尝试像这样设置DisplayMember和DisplayValue。其中“名称”/“值”是住宿类中的财产名称。
List<AccommodationEntity> relatedAccommodations = dt.listHolidayAccommodation(relatedHoliday);
accommodationList.DataSource = relatedAccommodations;
accommodationList.DisplayMember = "Name";
accommodationList.ValueMember = "Value";
<强>更新强>
确保textToShow
实际上是一个属性,而不仅仅是一个公共字段。