How can I use a more generic method to clean up the redundancy in the switch statement below?
I'm working on an ASP.NET webforms app that will have five identical user controls that I will be showing and hiding based on the value of a dropdown list. (I have already been down the path of trying to add and remove the controls dynamically--the issue of managing the view states for the controls would have been very complicated, so in the interest of shipping I'm opting for a fixed number of controls.)
The approach I'm currently using works but isn't very elegant:
protected void DisplayUserControls(int numberOfControls)
{
switch (numberOfControls)
{
case 2:
UserControl1.Visible = true;
UserControl2.Visible = true;
UserControl3.Visible = false;
break;
case 3:
UserControl1.Visible = true;
UserControl2.Visible = true;
UserControl3.Visible = true;
break;
default:
UserControl1.Visible = true;
UserControl2.Visible = false;
UserControl3.Visible = false;
break;
}
}
What are some options here? The best I can come up with is using numberOfControls to build the name of the control, but that seems hacky. Suggestions appreciated.
EDIT: I implemented a solution similar to the accepted answer below. I'm stuck on loading up the controls in the list. The commented out code is more along the lines of what I'd like to do but can't get it working. The uncommented code works. Suggestions?
private List<ShiftControl> PopulateShiftControlList()
{
ShiftControl shiftControlList = new List<ShiftControl>();
//ControlCollection panelControls = ShiftPanel.Controls;
//foreach (ShiftControl control in panelControls)
//{
// shiftControlList.Add(control);
//}
shiftControlList.Add(ShiftControl1);
shiftControlList.Add(ShiftControl2);
shiftControlList.Add(ShiftControl3);
shiftControlList.Add(ShiftControl4);
return shiftControlList;
}
UserControl
\$\endgroup\$MyProgram
. That was just to make it clear in my post what each item in thecase
statement was. \$\endgroup\$