Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Variable length string array

Tags:

arrays

string

c#

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!

like image 252
Dr. Hoads Avatar asked Aug 17 '26 00:08

Dr. Hoads


1 Answers

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" }
};
like image 108
Mark Byers Avatar answered Aug 18 '26 23:08

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!