但使用FindControl卻是要一層一層的去找找找....如下行範例.....
Control c=Page.FindControl("TabPanel1").FindPanel("tab_02").FindPanel("txtTest");
程式碼就會非常冗長..
網路上有高手把遞迴的方法帶入,下面程式碼是從網路上取得加以修改成自己習慣的撰寫方式
public static T FindControl(Control startingControl, string id) where T : Control
{
// 取得 T 的預設值,通常是 null
T found = default(T);
if (startingControl.Controls.Count > 0)
{
foreach (Control activeControl in startingControl.Controls)
{
if (activeControl is T)
{
found = activeControl as T;
if (string.Compare(id, found.ID, true) == 0) break;
else found = null;
}
else
{
found = FindControl(activeControl, id);
if (found != null) break;
}
}
}
return found;
}
最後show一下使用方式:
Control c = FindControl<TextBox>(this.Page, "txtTest");是不是清爽多了!!!!
優點:前端aspx異動也不怕要異動程式碼
光這一點就可以省下許多時間去茶水間泡杯咖啡囉~
參考出處:
1.你有用 FindControl 時找不到 Control (控制項) 的經驗嗎
2.程式碼出處
沒有留言:
張貼留言