Search code examples
c#dictionarycomboboxbindingsource

Why do I get, "Cannot bind to the new display member." with this code?


I have this code to assign the values of a Dictionary to a combo box:

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

At runtime, I get, "Cannot bind to the new display member." with this code, though, on this line:

comboBoxWeekToSchedule.ValueMember = "Value";

Why?


Solution

  • You can't bind ComboBox to fields. Try loading the DataSource after you define the DisplayMember and DisplayValue:

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