2013-05-30 61 views
2

我有一个数据库中包含一堆不同的控件的表。在我的Page_Init方法中,我需要根据正在传入的Session变量加载适当的控件。是否有更好的方法来完成此操作,然后使用一大堆if..else语句?我有大约15到20个不同的场景,所以我不想写20个if..else语句。任何帮助是极大的赞赏!替代if..else语句

DataTable的题为 “值” 有三列:(ID,名称,描述):

ID | Name | Description 
------------------- 
1 | A | First 
2 | B | Second 
3 | C | Third  

这里是我的代码:

ControlOne c1; 
ControlTwo c2; 
ControlThree c3; 

protected void Page_Init(object sender, EventArgs e) 
{ 
    DataSet DS = Client.GetInformation(Session["Number"].ToString()); 
    DataRow DR = DS.Tables["Value"].Rows[0]; 

    if (DR["Name"].ToString() == "A" && DR["Description"].ToString() == "First") 
    { 
     c1 = (ControlOne)LoadControl("~/ControlOne.ascx"); 
     panel1.Controls.Add(c1); 
    } 
    else if (DR["Name"].ToString() == "B" && DR["Description"].ToString() == "Second") 
    { 
     c2 = (ControlTwo)LoadControl("~/ControlTwo.ascx"); 
     panel1.Controls.Add(c2); 
    } 
    else if (DR["Name"].ToString() == "C" && DR["Description"].ToString() == "Third") 
    { 
     c3 = (ControlThree)LoadControl("~/ControlThree.ascx"); 
     panel1.Controls.Add(c3); 
    } 
    else if... //lists more scenarios here.. 
} 
+5

你的意思是一个switch语句? –

+0

使用字符串映射到类型。 –

+0

如何连接串并使用开关盒。 –

回答

0

您可以使用switch语句。

但是,有一个更好的方法。您的示例在数据库表中具有ID,名称,说明。所以保持名称字段与usercontrol名称相同,你可以这样做:

string controlName = dr["Name"]; 
c1 = LoadControl(string.Format("~/{0}.ascx", controlName)); 
panel1.Controls.Add(c1); 

希望这会有所帮助。

+0

非常感谢您的帮助!对此,我真的非常感激! –

0

在我看来,你可以使用一个开关声明,并且只对“名称”或“描述”进行测试。

7

你可以做这样的事情:

var controlsToLoad = new Dictionary<Tuple<string, string>, string>() 
{ 
    { Tuple.Create("A", "First"), "~/ControlOne.ascx" }, 
    { Tuple.Create("B", "Second"), "~/ControlTwo.ascx" }, 
    { Tuple.Create("C", "Third"), "~/ControlThree.ascx" }, 
    ... 
}; 

var key = Tuple.Create(DR["Name"].ToString(), DR["Description"].ToString()); 
if (controlsToLoad.ContainsKey(key)) 
{ 
    Control c = LoadControl(controlsToLoad[key]); 
    panel1.Controls.Add(c); 
} 

这是更紧凑,更容易比一个巨大的if..else或switch块读取。

+4

请注意,您可能希望字典是一个字段,而不是本地字典,只是因为无需在每次回发时重新创建该字典。 – Servy

+0

非常感谢您的帮助!这是一个非常好的主意,经过深思熟虑! –