newrev426
newrev426

Reputation: 29

When groupbox is on another groupbox function cannot find groupbox

The program I am making requires a lot of user input. A command is selected by the user and the corresponding groupbox is made visible and I save the current groupbox for later use. The code below works flawlessly IF the groupboxes are not overlapping in the GUI. What I want is to be able to stack all of the groupboxes on top of each other and this to still work.

for (int i = 0; i < funcCodes.Length; i++)
  {
    byte z = funcCodes[i];
    GroupBox gb = (GroupBox)Controls["gbDisplay_FC" + z];
    if (z == zcontrol.getFunctionCode())
    {
        gb.Visible = true;
        currentGB = gb;
    }
    else
        gb.Visible = false;
  }

The failure I get is when they are stacked gb becomes null (cant find the groupbox) Thanks for any help pretty new to C#.

Edit1: The below comment works as well as if you just change the location of the groupbox using the properties vs drag and drop that makes it a child.

Upvotes: 0

Views: 426

Answers (2)

Idle_Mind
Idle_Mind

Reputation: 39152

Do a search for your control name then using Controls.Find() like this:

        Control[] gbs = this.Controls.Find("gbDisplay_FC" + z.ToString(), true);
        if (gbs.Length > 0 && gbs[0] is GroupBox)
        {
            GroupBox gb = (GroupBox)gbs[0];
            // .. do something with "gb" ...
        }

This will work whether the GroupBoxes are contained directly by the Form, or are "stacked" causing them to be contained by one another.

Upvotes: 1

VladL
VladL

Reputation: 13043

Then simply add a null check

for (int i = 0; i < funcCodes.Length; i++)
  {
    byte z = funcCodes[i];
    GroupBox gb = (GroupBox)Controls["gbDisplay_FC" + z];


    if(gb == null)
      continue;


    if (z == zcontrol.getFunctionCode())
    {
        gb.Visible = true;
        currentGB = gb;
    }
    else
        gb.Visible = false;
  }

Upvotes: 0

Related Questions