【问题标题】:Populate comboBox from listBox values in C#从 C# 中的 listBox 值填充组合框
【发布时间】:2023-04-01 08:44:02
【问题描述】:

我无法解决这个问题。我需要从 listBox(C# 中的 Windows 窗体)中的值填充 comboBox 项目。
每次我在listbox 中添加值时,combobox 都会自动填充。

提前致谢。

这是代码,但现在可以使用

for (int i = 0; i < listBox1.Items.Count; i++)
        {
            comboBox1.Items.Add(listBox1.Items[i]);
        }

【问题讨论】:

  • 请使用您的代码示例更新您的帖子。特别是不工作的代码部分。
  • 请分享您的代码。
  • 您可以通过创建一个 BindingList 并将 ComboBox 的源分配给该 BindingList 来做到这一点,如果您想要一个工作示例,请告诉我
  • 谢谢,我需要一个工作示例,提前致谢
  • vincetlerry 你最初是如何填充组合框的......?

标签: c# combobox listbox listboxitem


【解决方案1】:
private BindingList<string> bindingList;

List<string> stringList = new List<string();
//populate the list any way you want for example
stringList.Add("Hello");
stringList.Add("Good Morning");

bindingList = new BindingList<string>(stringList);
this.comboBox1.DataSource = bindingList;
this.listBox1.DataSource = bindingList;

我建议使用循环加载 strngList 变量,或者如果数据来自数据库,则以这种方式加载字段,然后绑定到 ComboBox。

【讨论】:

  • 对不起,我的无能 DJ Kraze,但我不明白如何使用 listBox 中的值,因为必须从 ListBox 填充组合框。感谢您的耐心等待
  • @vincentlerry 如果你将它们都绑定到同一个 BindingList 并且 BindingList 使用“stringList”,你所要做的就是从 stringList 添加或删除项目,listBox 和 comboBox 将保持同步。您确实可以直接从列表框中添加/删除项目,您可以通过“stringList”来实现保持两个控件同步是您想要的吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-17
  • 2015-05-23
  • 1970-01-01
相关资源
最近更新 更多