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
Adrian magdas
source
to share
4 answers
You don't need to output the result from LoadControl.
This should do:
private Control GetControl()
{
string dynamicCtrl = CurrentItem.DynamicControl;
string path = SomeClass.DynamicControls[dynamicCtrl];
Control ctrl = LoadControl(path);
return ctrl;
}
+9
Magnus
source
to share
You probably want something like this (pseudo-ish code):
foreach key in dictionary if key = dynamicControl then ctrl = (Type.GetType (key)) LoadControl (dictionary.get (key)) end if next
+1
Adam pope
source
to share
Can't you just use foreach on your dictionary and execute your test and LoadControl there?
0
Will dean
source
to share
This will not help because a switch is needed to select the correct type of control.
0
Adrian magdas
source
to share