Refactoring needed
I have a page where I have to load controls dynamically based on user selection. Let's say that I have something like this:
public static readonly Dictionary<string, string> DynamicControls = new Dictionary<string, string>
{
{ "UserCtrl1", "~/Controls/UserCtrl1.ascx" },
{ "UserCtrl2", "~/Controls/UserCtrl2.ascx" },
{ "UserCtrl3", "~/Controls/UserCtrl3.ascx" },
{ "UserCtrl4", "~/Controls/UserCtrl4.ascx"}
};
Now let's say that on the page where the controls are loaded, the code looks something like this:
protected void Page_Load(object sender, EventArgs e)
{
SomePanel.Controls.Add(GetControl());
}
private Control GetControl()
{
string dynamicCtrl = CurrentItem.DynamicControl;
string path = SomeClass.DynamicControls[dynamicCtrl];
Control ctrl = null;
//TODO: find a better way to load the controls
switch (dynamicCtrl)
{
case "UserCtrl1":
{
ctrl = (UserCtrl1)LoadControl(path);
}
break;
case "UserCtrl2":
{
ctrl = (UserCtrl2)LoadControl(path);
}
break;
case "UserCtrl3":
{
ctrl = (UserCtrl3)LoadControl(path);
}
break;
default:
{
throw new ApplicationException("Invalid dynamic control added.");
}
}
return ctrl;
}
There are registered entries on the page. Any idea how I can get rid of this ugly switch statement?
0
source to share