【问题标题】:Combobox contents based on another combobox value基于另一个组合框值的组合框内容
【发布时间】:2015-09-09 16:59:25
【问题描述】:

我有两个组合框,其中第一个有类别(我可以从源文件轻松填充)。诀窍是让第二个组合框仅显示与第一个组合框中所选类别相关联的项目。例如:

cb1 由源文件填充,类别值为 1、2、3 和 4,cb2 填充值为 A、B、C、D、E、F、G、H

我没有做的是限制在 cb2 中看到的内容。所以当cb1的值为“1”时,我只希望“A”和“B”在cb2中可见,如果cb1变为“2”我只希望“C”和“D”可见。

【问题讨论】:

标签: c# .net combobox


【解决方案1】:

对于winforms:

如果您有一个带有 2 个组合框(cb1、cb2)的表单,您可以使用这样的东西吗? (显然已修改为支持您的数据对象)。

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //create a list for data items
            List<MyComboBoxItem> cb1Items = new List<MyComboBoxItem>();

            //assign sub items
            cb1Items.Add(new MyComboBoxItem("1")
            {
                SubItems = { new MyComboBoxItem("A"), new MyComboBoxItem("B") }
            });

            cb1Items.Add(new MyComboBoxItem("2")
            {
                SubItems = { new MyComboBoxItem("C"), new MyComboBoxItem("D") }
            });

            cb1Items.Add(new MyComboBoxItem("3")
            {
                SubItems = { new MyComboBoxItem("E"), new MyComboBoxItem("F") }
            });

            cb1Items.Add(new MyComboBoxItem("4")
            {
                SubItems = { new MyComboBoxItem("G"), new MyComboBoxItem("H") }
            });

            //load data items into combobox 1
            cb1.Items.AddRange(cb1Items.ToArray());
        }

        private void cb1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //get the combobox item
            MyComboBoxItem item = (sender as ComboBox).SelectedItem as MyComboBoxItem;

            //make sure no shinanigans are going on
            if (item == null)
                return;

            //clear out combobox 2
            cb2.Items.Clear();

            //add sub items
            cb2.Items.AddRange(item.SubItems.ToArray());
        }
    }

    public class MyComboBoxItem
    {
        public string Name;
        public List<MyComboBoxItem> SubItems = new List<MyComboBoxItem>();

        public MyComboBoxItem(string name)
        {
            this.Name = name;
        }

        public override string ToString()
        {
            return Name;
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-22
    • 2014-11-22
    • 2012-02-29
    相关资源
    最近更新 更多