2011-04-06 31 views
0

我在我的類文件中寫入一個連接到數據庫並加載數據的函數。我想傳遞一個查詢,asp.net控件類型和控件id給函數,這樣當我調用函數時,它可以根據控件類型加載數據(我將爲每個控件類型編寫一個開關案例) 。有些事情是這樣的:如何在功能中傳遞asp.net服務器控件類型?

public static string LoadData(string qry, Controltype, controlId) 
{ 


string connstring = "......"; 
OleDbDataAdapter da = new OleDbDataAdapter 
DataTable dt = new DataTable(); 
OleDbConnection con = new OleDbConnection(connstring); 
con.Open(); 
da = new OleDbDataAdapter(qry, connstring); 
dt = new DataTable(); 
da.Fill(dt); 
switch(controltype) 
{ 
case DropDownList: 
     ...... 
     ...... 
break; 

case GridView: 
     ...... 
     ...... 
break; 
} 

誰能告訴我怎樣才能通過Controltype和控件ID在該功能。

回答

1

這裏是你如何能做到這:

protected void Page_Load(object sender, EventArgs e) 
{ 
    LoadData(ddlList, ddlList.ID); 
    LoadData(chkBxList, chkBxList.ID); 
} 

void LoadData(WebControl control, string id) 
{ 
    string typeName = control.GetType().Name; 
    switch (typeName) 
    { 
     case "DropDownList": 
       //do something here 
      break; 
     case "CheckBoxList": 
      //do something here 
      break; 
    } 
} 

我有一個的CheckBoxList和DropDownList的在我的HTML代碼如下:

<asp:CheckBoxList ID="chkBxList" runat="server"> 
    </asp:CheckBoxList> 
    <asp:DropDownList ID="ddlList" runat="server"/> 

希望這有助於...

+0

Hi Sajoshi,This see毫秒工作。但是一個小的改變,上面的函數LoadData是在一個單獨的類文件中,所以我在添加項目到控制時遇到問題。我需要寫control.Items.Add(列表)。但它不能提供智能感知。我能否知道添加項目到列表的其他方式。或者爲什麼它不允許我添加項目?我想控制不完全是一個下拉列表。 – hima 2011-04-06 09:14:35

-1

嘗試此代碼:

DropDownList Ll = new DropDownList(); 
Ll = (DropDownList)control; 
+0

這與OP的問題有什麼關係? – 2012-10-11 20:04:46

相關問題