Binding a generic List to a ComboBox

后端 未结 6 1555
轻奢々
轻奢々 2020-12-16 13:07

I have a ComboBox and I want to bind a generic List to it. Can anyone see why the code below won\'t work? The binding source has data in it, but it won\'t fill the ComboBox

6条回答
  •  -上瘾入骨i
    2020-12-16 13:55

    Using Yuriy Faktorovich's code above as a basis, here is how to get a list of dates in LongDateString format for a given number of weeks, and assign them to a combo box. This uses "Monday" but you can simply replace "Monday" with any other DOW to suit your purposes:

    private void PopulateSchedulableWeeks()
    {
        int WEEKS_COUNT = 13;
        List schedulableWeeks = PlatypusUtils.GetWeekBeginnings(WEEKS_COUNT).ToList();
        BindingSource bs = new BindingSource();
        bs.DataSource = schedulableWeeks;
        comboBoxWeekToSchedule.DataSource = bs;
    }
    
    public static List GetWeekBeginnings(int countOfWeeks)
    {
        // from http://stackoverflow.com/questions/6346119/datetime-get-next-tuesday
        DateTime today = DateTime.Today;
        // The (... + 7) % 7 ensures we end up with a value in the range [0, 6]
        int daysUntilMonday = ((int)DayOfWeek.Monday - (int)today.DayOfWeek + 7) % 7;
        DateTime nextMonday = today.AddDays(daysUntilMonday);
    
        List mondays = new List();
        mondays.Add(nextMonday.ToLongDateString());
    
        for (int i = 0; i < countOfWeeks; i++)
        {
            nextMonday = nextMonday.AddDays(7);
            mondays.Add(nextMonday.ToLongDateString());
        }
        return mondays;
    }
    

    ...and, if you want to add the actual date to the combo box, too, you can use a Dictionary like so:

        int WEEKS_TO_OFFER_COUNT = 13;
        BindingSource bs = new BindingSource();
        Dictionary schedulableWeeks = AYttFMConstsAndUtils.GetWeekBeginningsDict(WEEKS_TO_OFFER_COUNT);             bs.DataSource = schedulableWeeks;
        comboBoxWeekToSchedule.DataSource = bs;
        comboBoxWeekToSchedule.DisplayMember = "Key";
        comboBoxWeekToSchedule.ValueMember = "Value";
    
    public static Dictionary GetWeekBeginningsDict(int countOfWeeks)
    {
        DateTime today = DateTime.Today;
        // The (... + 7) % 7 ensures we end up with a value in the range [0, 6]
        int daysUntilMonday = ((int)DayOfWeek.Monday - (int)today.DayOfWeek + 7) % 7;
        DateTime nextMonday = today.AddDays(daysUntilMonday);
    
        Dictionary mondays = new Dictionary();
        mondays.Add(nextMonday.ToLongDateString(), nextMonday);
    
        for (int i = 0; i < countOfWeeks; i++)
        {
            nextMonday = nextMonday.AddDays(7);
            mondays.Add(nextMonday.ToLongDateString(), nextMonday);
        }
        return mondays;
    }
    

提交回复
热议问题