C# 将通用 List<string> 绑定到 ComboBox

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1610695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 19:22:32  来源:igfitidea点击:

Binding a generic List<string> to a ComboBox

c#winformsdata-bindingbinding

提问by Nathan

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 data source.

我有一个 ComboBox,我想将一个通用列表绑定到它。谁能看出为什么下面的代码不起作用?绑定源中有数据,但不会填充 ComboBox 数据源。

FillCbxProject(DownloadData Down)
{
  BindingSource bindingSource = new BindingSource();
  bindingSource.DataSource = Down.ProjectList;
  cbxProjectd.DataSource = bindingSource;
}

On a side note: Is it bad to pass around an instance of a class?

附带说明:传递类的实例是否不好?

Thanks!

谢谢!

采纳答案by Yuriy Faktorovich

You need to call the Bind method:

您需要调用 Bind 方法:

cbxProjectd.DataBind();

If this is for winforms then you need to make sure what you have is being called, the following works:

如果这是针对 winforms,那么你需要确保你所拥有的被调用,以下工作:

BindingSource bs = new BindingSource();
bs.DataSource = new List<string> { "test1", "test2" };
comboBox1.DataSource = bs;

Although you can set the ComboBox's DataSource directly with the list.

虽然您可以直接使用列表设置 ComboBox 的数据源。

回答by Bkillnest

this is the simple way (it works correctly):

这是简单的方法(它工作正常):

List<string> my_list = new List<string>();
my_list.Add("item 1");
my_list.Add("item 2");
my_list.Add("item 3");
my_list.Add("item 4");
my_list.Add("item 5");
comboBox1.DataSource = my_list;

回答by Bhupinder

BindingSource bs = new BindingSource();
bs.DataSource = getprojectname();
comboBox1 = new ComboBox();
comboBox1.DataSource = bs;

回答by B. Clay Shannon

Here is a rather simple way that doesn't use BindingSource:

这是一种不使用 BindingSource 的相当简单的方法:

first, add the generic list of string, perhaps to a "consts/utils" class:

首先,将字符串的通用列表添加到“consts/utils”类中:

public static List<string> Months = new List<string>
{
   "Jan",
   "Feb",
   "Mar",
   "Apr",
   "May",
   "Jun",
   "Jul",
   "Aug",
   "Sep",
   "Oct",
   "Nov",
   "Dec"
};

And here's how you add those strings to a combo box:

以下是将这些字符串添加到组合框的方法:

comboBoxMonth.Items.AddRange(UsageRptConstsAndUtils.Months.ToArray<object>());

回答by B. Clay Shannon

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:

使用上面 Yuriy Faktorovich 的代码作为基础,这里是如何获取给定周数的 LongDateString 格式的日期列表,并将它们分配给组合框。这使用“星期一”,但您可以简单地用任何其他 DOW 替换“星期一”以满足您的目的:

private void PopulateSchedulableWeeks()
{
    int WEEKS_COUNT = 13;
    List<String> schedulableWeeks = PlatypusUtils.GetWeekBeginnings(WEEKS_COUNT).ToList();
    BindingSource bs = new BindingSource();
    bs.DataSource = schedulableWeeks;
    comboBoxWeekToSchedule.DataSource = bs;
}

public static List<String> 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<String> mondays = new List<string>();
    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<String, DateTime> schedulableWeeks = AYttFMConstsAndUtils.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;
    // 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<String, DateTime> mondays = new Dictionary<String, DateTime>();
    mondays.Add(nextMonday.ToLongDateString(), nextMonday);

    for (int i = 0; i < countOfWeeks; i++)
    {
        nextMonday = nextMonday.AddDays(7);
        mondays.Add(nextMonday.ToLongDateString(), nextMonday);
    }
    return mondays;
}

回答by Eldar Gerfanov

If anyone finds this necro thread, make sure your list does not contain null items. Otherwise binding will fail silently!

如果有人发现此死灵线程,请确保您的列表不包含空项目。否则绑定将无声无息地失败!

//This will not work!
comboBox1.DataSource = new List<string> { "test1", null, "test2" };

//This is legit!
comboBox1.DataSource = new List<string> { "test1", "", "test2" };