如何将字典分配给组合框的项目(显示和值成员)?

时间:2016-02-07 22:55:15

标签: c# dictionary combobox

我知道如何将查询中的值分配给ListBox的Display和Value成员:

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";
        }
    }
}

...以及如何将单个值分配给ComboBox,如下所示:

List<String> schedulableWeeks = PlatypusUtils.GetWeekBeginnings(WEEKS_COUNT).ToList();
BindingSource bs = new BindingSource();
bs.DataSource = schedulableWeeks;
comboBoxWeekToSchedule.DataSource = bs;

...但是如何将Dictionary分配给组合框,我的Dictionary的字符串值为Display值,DateTime为ValueMember?我试过这个:

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];

...认为我可以通过Dictionary元素0访问字符串,并通过元素1访问DateTime,但它甚至不编译(“参数1:无法从'int'转换为'string'”) - 两条线的错误信息相同。

3 个答案:

答案 0 :(得分:1)

您是否尝试过使用toDictionary()?我不确定PlatypusUtils.GetWeekBeginningsDict究竟返回了什么,但我猜这可以解决问题。

Dictionary<String, DateTime> schedulableWeeks = PlatypusUtils.GetWeekBeginningsDict(WEEKS_TO_OFFER_COUNT).ToDictionary(x => x.Key);

也可能是KeyValuePair的绑定源问题:

comboBoxWeekToSchedule.DisplayMember = "Key";
comboBoxWeekToSchedule.ValueMember = "Value";

答案 1 :(得分:1)

这样的事情应该有效:

std::signbit

基本上,字典中的每个项目都有一个“键”和一个“值”,因为字典中的每个项目都是BindingSource bs = new BindingSource(); bs.DataSource = schedulableWeeks; comboBoxWeekToSchedule.DataSource = bs; comboBoxWeekToSchedule.DisplayMember = "Key"; comboBoxWeekToSchedule.ValueMember = "Value";

答案 2 :(得分:1)

尝试设置组合框的键和值,如下所示:

comboBoxWeekToSchedule.DisplayMember = "Key";
comboBoxWeekToSchedule.ValueMember = "Value";