如何将字典分配给组合框的项目(显示和值成员)
本文关键字:显示 项目 成员 字典 分配 组合 | 更新日期: 2023-09-27 18:33:40
我知道如何将查询中的值分配给 ListBox 的显示和值成员:
using (SqlConnection con = new SqlConnection(ReportRunnerConstsAndUtils.CPSConnStr))
{
using (SqlCommand cmd = new SqlCommand(ReportRunnerConstsAndUtils.SelectUnitsQuery, con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
((ListBox)checkedListBoxUnits).DataSource = dt;
((ListBox)checkedListBoxUnits).DisplayMember = "Unit";
((ListBox)checkedListBoxUnits).ValueMember = "Unit";
}
}
}
。以及如何像这样为组合框分配单个值:
List<String> schedulableWeeks = PlatypusUtils.GetWeekBeginnings(WEEKS_COUNT).ToList();
BindingSource bs = new BindingSource();
bs.DataSource = schedulableWeeks;
comboBoxWeekToSchedule.DataSource = bs;
。但是如何将字典分配给组合框,将字典的字符串值作为显示值,将日期时间作为值成员?我试过这个:
Dictionary<String, DateTime> schedulableWeeks =
PlatypusUtils.GetWeekBeginningsDict(WEEKS_TO_OFFER_COUNT);
BindingSource bs = new BindingSource();
bs.DataSource = schedulableWeeks;
comboBoxWeekToSchedule.DataSource = bs;
comboBoxWeekToSchedule.DisplayMember = schedulableWeeks[0];
comboBoxWeekToSchedule.ValueMember = schedulableWeeks[1];
。认为我可以通过字典元素 0 访问字符串,通过元素 1 访问 DateTime,但它甚至无法编译("参数 1:无法从'int'转换为'字符串'") - 两行的错误消息相同。
尝试为组合框设置键和值,如下所示:
comboBoxWeekToSchedule.DisplayMember = "Key";
comboBoxWeekToSchedule.ValueMember = "Value";
这样的事情应该有效:
BindingSource bs = new BindingSource();
bs.DataSource = schedulableWeeks;
comboBoxWeekToSchedule.DataSource = bs;
comboBoxWeekToSchedule.DisplayMember = "Key";
comboBoxWeekToSchedule.ValueMember = "Value";
基本上,字典中的每个项目都有一个"键"和一个"值",因为字典中的每个项目都是一个KeyValuePair<string,DateTime>
你试过使用toDictionary()
吗?我不确定PlatypusUtils.GetWeekBeginningsDict到底返回了什么,但我猜这可以解决问题。
Dictionary<String, DateTime> schedulableWeeks = PlatypusUtils.GetWeekBeginningsDict(WEEKS_TO_OFFER_COUNT).ToDictionary(x => x.Key);
也可能是 KeyValuePair 的绑定源问题:
comboBoxWeekToSchedule.DisplayMember = "Key";
comboBoxWeekToSchedule.ValueMember = "Value";