0

I have two arrays of 16 checkboxes that I want to have gradually checked when a for statement runs. It looks like this:

public void Cycle()
{
   if (host == false)
        {
            CheckBox[] cboxes = relayRow.CheckBoxes;
        }                
        else if (host == true)
        {
            CheckBox[] cboxes = relayRow2.CheckBoxes;
        }
   for (int i = 0; i < 16; i++)
        {            
            cboxes[i].Checked = true;
        }
}

I am getting a red line under the 'cboxes' in the for statement saying "The name 'cboxes' does not exist in the current context." If I only use one at a time, it works perfectly, so there shouldn't be a problem with my arrays. Working one at a time is as follows:

  public void Cycle()
    {            
        CheckBox[] cboxes = relayRow.CheckBoxes;

        for (int i = 0; i < 16; i++)
        {
            cboxes[i].Checked = true;
        }
    }

There should also be not problem with my boolean 'host' since I have used it in other places and it works as intended. I'm just trying to switch between which array of 16 will be checked. Thanks in advance.

2 Answers 2

2

You just need to declare the variable outside of the if statement:

public void Cycle()
{
    CheckBox[] cboxes = null;
    if (host == false)
    {
        cboxes = relayRow.CheckBoxes;
    }                
    else if (host == true)
    {
        cboxes = relayRow2.CheckBoxes;
    }
    for (int i = 0; i < 16; i++)
    {            
        cboxes[i].Checked = true;
    }
}

or just

public void Cycle()
{
    CheckBox[] cboxes = host ? relayRow2.CheckBoxes : relayRow.CheckBoxes;
    for (int i = 0; i < 16; i++)
    {            
         cboxes[i].Checked = true;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Slight Variation to D Stanley's answer, not sure if you NEED to use arrays and a for loop which forces you to hard code the number of checkboxes but this shoud work as well:

  public void Cycle()
    {
        var cboxes = host ? relayRow2.CheckBoxes : relayRow.CheckBoxes;
        cboxes = (from checkBox in cboxes.ToList()
            select new CheckBox { Checked = true}).ToArray();
    }

P.S. I don't have enough reputation points to comment otherwise I would have just commented your answer D Stanley and upticked (sorry!)

Comments

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.