0
votes

I have a Windows Forms app that contains a groupbox with about 30 controls. For the sake of example, let's say that there are 15 labels and 15 textboxes. This groupbox and the controls in it are used to display three different scenarios:

Scenario 1 - requires all of the controls to be visible

Scenario 2 - requires label/textbox #1, 4, 11 and 14 to be visible and the others to be hidden

Scenario 3 - requires label/textbox #3, 9, 11 and 13 to be visible and the others to be hidden

Scenario 1 is obviously straightforward enough. But the other two scenarios are a little more work. Originally, I wrote code to manually show/hide each of the controls like this:

ConfigureUIForScenario2()
{
    label1.visible = true;
    textbox1.visible = true;
    label2.visible = false;
    textbox2.visible = false;
    label3.visible = false;
    textbox3.visible = false;
    label4.visible = true;
    textbox4.visible = true;
    ...
}

That was extremely unwieldy and it just seems like there must be another way. I was looking at panels to organize the controls but since the controls that need to be shown/hidden in scenario 2 and 3 aren't generally adjacent to one another, the best that that idea yielded was being able to put each label and corresponding textbox into a panel and show/hide the panel. Setting the visibility of 15 panels is, of course, less work than manually setting 30 individual controls, but I'm wondering if there's a better way still? I am now considering having three panels (one for each scenario) and only adding the necessary controls to each panel. I'm wondering if there's any sort of best practice with regard to layout problems like this?

1
You should name your controls.SLaks
Oh, they're named, I was just using default names for the sake of space and clarity.bmt22033

1 Answers

2
votes

You can create a List<Control> or a Control[] for each scenario, then loop through the controls in the lists and set their Visible properties as appropriate.