3
\$\begingroup\$

I have the following code in a portion of my program that hides/shows certain elements based on the status of a certain checkbox:

private void enableFolderVariableRemoval_CheckedChanged(object sender, EventArgs e)
{
    if (enableFolderVariableRemoval.Checked)
    {
        cleanFolderTextPanel.Visible = true;
        cleanTextPanel.Visible = true;
    }
    else
    {
        cleanFolderTextPanel.Visible = false;
        if (cleanFilenameTextPanel.Visible == false)
        {
            cleanTextPanel.Visible = false;
        }
    }
}

Is there a better way to handle this without a whole bunch of conditionals that set other controls to hide/show?

\$\endgroup\$
6
\$\begingroup\$

Not sure if there are any other constraints but here is one possible solution:

private void enableFolderVariableRemoval_CheckedChanged(object sender, EventArgs e)
{
    cleanFolderTextPanel.Visible = enableFolderVariableRemoval.Checked; 
    cleanTextPanel.Visible = cleanFolderTextPanel.Visible || cleanFilenameTextPanel.Visible;        
}
\$\endgroup\$
2
\$\begingroup\$

I'm not sure what the logic is in your code, the else and nested if in it is really confusing. But from what I can understand:

You can set the Visible Attribute for cleanFolderTextPanel straight from the checked value of enableFolderVariableRemoval.

The Visible Attribute for cleanTextPanel can then be calculated using a new Method and an inline if:

private void enableFolderVariableRemoval_CheckedChanged(object sender, EventArgs e)
{
    var enableFolderVariableRemoval = enableFolderVariableRemoval.Checked;

    cleanFolderTextPanel.Visible = enableFolderVariableRemoval;
    cleanTextPanel.Visible = CleanTextPanelShouldBeHidden(enableFolderVariableRemoval ) ? false : cleanTextPanel.Visible
}

...

private static void CleanTextPanelShouldBeHidden(bool enableFolderVariableRemoval)
{
     return !cleanFilenameTextPanel.Visible && !enableFolderVariableRemoval
}
\$\endgroup\$
0
\$\begingroup\$

Assuming you already moved your controls into logical panels, Perhaps you are asking a more general question: how do you prevent the following construct from going wild?

Some Event...
If GUI = 1
    Panel1.Show()
    Panel2.Hide()
    Panel3.Hide()
    ...
If GUI = 2
    Panel1.Hide()
    Panel2.Show()
    ...
If GUI = 3
    ...

Make the GUI Panels implement a View_I interface which has a .Show() and .Hide() methods, then the code becomes more like:

Some Event...
// hide the previous View if one exists
If View_I != Null
    View_I.Hide()

If GUI = 1
    View_I = Panel1
If GUI = 2
   View_I = Panel2
    ...
// Show the new View
View_I.Show() 
    ...

Now you can add other Panels without code management proliferation.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.