Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use array value for case switching (not array number)

How do you use the VALUE of an array number as opposed to what number in the array it is for determining case? In my code:

for (int x = 0; x < 3; x++)
        {
            switch (position[x])
            {
                case 0:
                    label1.Text = people[x];
                    break;
                case 1:
                    label2.Text = people[x];
                    break;
                case 2:
                    label3.Text = people[x];
                    break;
            }
        }

When this is run, it uses the x in position[] as opposed to position[x]'s value for determining which case to use. For instance, when x is 0, but position[x]'s value is 1, it uses case 0. How do I get the value instead?

EDIT: My code was indeed the problem.... For some reason debugging early in the morning has the effect of creating false images... :P As an FYI, here was the correct code...

for (int x = 0; x < 3; x++)
        {
            if (position[x] == 2)
            {
                position[x] = 0;
            }

            else
            position[x]++;

        }

        for (int x = 0; x < 3; x++)
        {
            int val = position[x];
            switch (val)
            {
                case 0:
                    label1.Text = people[x];
                    break;
                case 1:
                    label2.Text = people[x];
                    break;
                case 2:
                    label3.Text = people[x];
                    break;
            }

In the upper first appearance of position[x], I instead had placed only x. Thanks for all the help!

like image 294
Bloodyaugust Avatar asked Jan 27 '10 14:01

Bloodyaugust


1 Answers

Try this:

    for (int x = 0; x < 3; x++)
    {
        int val = position[x];
        switch (val)
        {
            case 0:
                label1.Text = people[x];
                break;
            case 1:
                label2.Text = people[x];
                break;
            case 2:
                label3.Text = people[x];
                break;
        }
    }

Maybe something easier would be to say:

for(int x = 0; x < 3; x++)
{
    Label label = MyForm.ActiveForm.Controls["label" + position[x]] as Label;
    if (label != null) label.Text = people[x];
}
like image 76
hunter Avatar answered Sep 21 '22 11:09

hunter