Combobox的元素过滤

时间:2012-07-24 12:03:33

标签: c# combobox

我有combobox1和comboox2,在combobox1中,我的元素是A,B,C和组合框2 1,2,3,4,5,6 ......

A related 1,2,3 and B related 3,4 and C related 5,6.

When I choose "A" I want to see just 1,2,3 ; when select "B" just 3,4 etc.

我怎么能想象呢?

我试图在选定的索引中更改,但我没有

1 个答案:

答案 0 :(得分:2)

试试这个,做一个这样的课:

public class Data
    {
        public string Name { get; set; }
        public List<int> Values { get; set; }
    }

然后在你的表单中有一个这样的变量:

private List<Data> data = new List<Data>
        {
            new Data{Name="A",Values=new List<int>{1,2,3}},
            new Data{Name="B",Values=new List<int>{4,5}},
            new Data{Name="C",Values=new List<int>{6,7}},
        };

然后在表单的构造函数中:

comboBox1.DisplayMember = "Name";
            comboBox1.DataSource = data;            
            comboBox1.SelectedIndex = 0;

然后在combobox1的selectedindex更改事件中执行如下操作:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = comboBox1.SelectedIndex;
            comboBox2.DataSource = data[index].Values;
        }

它应该有用。