根据comboBox1选择,我填充comboBox2。comboBox2具有可变数量的列表项。目前,我手动执行此操作,如下所示:
string[] str1 = { "item1", "item2" }
string[] str2 = { "item1", "item2", "item3" , "item4" }等。
if (cbox1.SelectedIndex == 0)
{
cbox2.Items.AddRange(str1);
}
if (cbox1.SelectedIndex == 1)
{
cbox2.Items.AddRange(str2);
}等。
虽然这是可行的,但我有4个下拉列表和13个可能的选择。我更喜欢用一个字符串数组来做这件事,这样我就可以去掉所有的if,只需对每个SelectedIndexChanged执行以下操作:
cbox2.Items.AddRange(str[cbox1.SelectedIndex]);但我不确定我是否可以用可变长度的字符串做到这一点。执行以下操作时出现错误:
string[,] str = { { "Item1", "Item2"},{"Item1", "Item2", "Item3", "Item4"} };有没有办法做到这一点?
谢谢!
发布于 2011-12-14 07:04:39
您已经发现在这种情况下不能使用multidimensional array,因为您的数组具有不同的长度。但是,您可以使用jagged array:
string[][] str =
{
new string[] { "Item1", "Item2" },
new string[] { "Item1", "Item2", "Item3", "Item4" }
};发布于 2011-12-14 07:13:02
您可以使用字典并将SelectedIndex值映射到字符串数组(或者更好的IEnumerable<string>):
IDictionary<int, string[]> values = new Dictionary<int, string[]>
{
{0, new[] {"item1", "item2"}},
{1, new[] {"item3", "item4", "item5"}},
};
...
string[] items = values[1];发布于 2011-12-14 07:20:37
你也可以使用字典来实现你的目标:
Dictionary<int, string[]> itemChoices = new Dictionary<int,string>()
{
{ 1, new [] { "Item1", "Item2" }},
{ 2, new [] { "Item1", "Item2", "Item3", "Item4" }}
};然后,您可以简单地调用:
cbox1.Items.AddRange(itemChoices[cbox1]);
cbox2.Items.AddRange(itemChoices[cbox2]);https://stackoverflow.com/questions/8497475
复制相似问题