3

Based on comboBox1 selection, I populate comboBox2. The comboBox2 has a variable quantity of list items. Currently I am doing this manually like this:

string[] str1 = { "item1", "item2" }
string[] str2 = { "item1", "item2", "item3" , "item4" }

etc.

if (cbox1.SelectedIndex == 0)
{
       cbox2.Items.AddRange(str1);
}
if (cbox1.SelectedIndex == 1)
{
       cbox2.Items.AddRange(str2);
}

etc.

Although this works, I have events for 4 drop downs and 13 possible choices for each. This makes for a lot of if's. I would prefer to do this with an array of strings so that I can get rid of all of the if's and just do the following for each SelectedIndexChanged:

cbox2.Items.AddRange(str[cbox1.SelectedIndex]);

but I am not sure if I can do this with the variable lengths of the strings. I get errors when doing:

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

Is there a way to do this?

Thanks!

3 Answers 3

7

You have already discovered that you cannot use a multidimensional array in this situation, because your arrays have different lengths. However you could use a jagged array instead:

string[][] str =
{
    new string[] { "Item1", "Item2" },
    new string[] { "Item1", "Item2", "Item3", "Item4" }
};
Sign up to request clarification or add additional context in comments.

Comments

1

You can use a Dictionary and map your SelectedIndex values to string arrays (or even better, IEnumerable<string>):

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

1 Comment

I had not thought of this, I will at least try this solution as well.
1

You could also use a dictionary to accomplish your goal:

Dictionary<int, string[]> itemChoices = new Dictionary<int,string>()
{
    { 1, new [] { "Item1", "Item2" }},
    { 2, new [] { "Item1", "Item2", "Item3", "Item4" }}
};

Then you can simply call:

cbox1.Items.AddRange(itemChoices[cbox1]);
cbox2.Items.AddRange(itemChoices[cbox2]);

2 Comments

and apparently @Strillo beat me to clicking post (I was originally going to use LINQ); though my implementation is slightly different.
Thanks also for your solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.