[英]Combobox contents based on another combobox value
I have two comboboxes where the first one has categories (and I can fill that easily from the source file). 我有两个组合框,其中第一个组合框具有类别(我可以从源文件轻松填充该组合框)。 The trick is having the second combobox show only the items that are associated with the chosen category from the first combobox. 诀窍是让第二个组合框仅显示与从第一个组合框选择的类别关联的项目。 For example: 例如:
cb1 is populated from a sourcefile with the category values 1, 2, 3 & 4 and cb2 is populated with values A,B,C,D,E,F,G,H 从源文件中填充类别值分别为1、2、3和4的cb1,并使用值A,B,C,D,E,F,G,H填充cb2
What I am failing at doing is limiting what is seen in cb2. 我无法做的是限制cb2中看到的内容。 So when cb1's value is "1", I only want "A" and "B" to be visible in cb2, and if cb1 changes to "2" I only want "C" and "D" to be visible. 因此,当cb1的值为“ 1”时,我只希望在cb2中可见“ A”和“ B”,并且如果cb1更改为“ 2”,我只希望“ C”和“ D”可见。
For winforms : 对于Winforms:
If you have a form with 2 combo boxes (cb1, cb2) you could use something like this? 如果您有一个带有2个组合框的表单(cb1,cb2),您可以使用类似的内容吗? (obviously modified to support your data objects). (显然已修改为支持您的数据对象)。
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.