我有这段代码可以将字典的值分配给组合框:
private void PopulateComboBoxWithSchedulableWeeks()
{
int WEEKS_TO_OFFER_COUNT = 13;
BindingSource bs = new BindingSource();
Dictionary<String, DateTime> schedulableWeeks =
GetWeekBeginningsDict(WEEKS_TO_OFFER_COUNT);
bs.DataSource = schedulableWeeks;
comboBoxWeekToSchedule.DataSource = bs;
comboBoxWeekToSchedule.DisplayMember = "Key";
comboBoxWeekToSchedule.ValueMember = "Value";
}
public static Dictionary<String, DateTime> GetWeekBeginningsDict(int
countOfWeeks)
{
DateTime today = DateTime.Today;
int daysUntilMonday = ((int)DayOfWeek.Monday - (int)today.DayOfWeek + 7)
% 7;
DateTime nextMonday = today.AddDays(daysUntilMonday);
Dictionary<String, DateTime> mondays = new Dictionary<String, DateTime>
();
if (!IsAssemblyOrConventionWeek(nextMonday))
{
mondays.Add(nextMonday.ToLongDateString(), nextMonday);
}
for (int i = 0; i < countOfWeeks; i++)
{
nextMonday = nextMonday.AddDays(7);
if (!IsAssemblyOrConventionWeek(nextMonday))
{
mondays.Add(nextMonday.ToLongDateString(), nextMonday);
}
}
return mondays;
}
在运行时,我得到“无法绑定(bind)到新的显示成员。”但是,在这一行中使用此代码:
comboBoxWeekToSchedule.ValueMember = "Value";
为什么?
请您参考如下方法:
您不能将 ComboBox 绑定(bind)到字段。 在定义 DisplayMember 和 DisplayValue 后尝试加载 DataSource:
comboBoxWeekToSchedule.DisplayMember = "Key";
comboBoxWeekToSchedule.ValueMember = "Value";
comboBoxWeekToSchedule.DataSource = bs;
