2011-12-13 263 views
3

基於comboBox1選擇,我填充comboBox2。組合框2具有可變數量的列表項目。目前,我手動這樣做是這樣的:C#可變長度字符串數組

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"} }; 

有沒有辦法做到這一點?

謝謝!

回答

7

在這種情況下,您已經發現您不能使用multidimensional array,因爲您的陣列具有不同的長度。然而,你可以使用一個jagged array來代替:

string[][] str = 
{ 
    new string[] { "Item1", "Item2" }, 
    new string[] { "Item1", "Item2", "Item3", "Item4" } 
}; 
+0

完美!謝謝! – 2011-12-13 23:39:38

1

您可以使用字典和你的SelectedIndex值映射到字符串數組(甚至更好,IEnumerable<string>):

IDictionary<int, string[]> values = new Dictionary<int, string[]> 
           { 
            {0, new[] {"item1", "item2"}}, 
            {1, new[] {"item3", "item4", "item5"}}, 
           }; 
... 
string[] items = values[1]; 
+0

我沒有想到這一點,我至少會嘗試這種解決方案。 – 2011-12-13 23:41:16

1

你也可以用字典來實現你的目標:

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]); 
+0

顯然@Strillo打我點擊帖子(我原本打算使用LINQ);儘管我的實現稍有不同。 – 2011-12-13 23:22:54