【MyNote】FindControl(轉自will保哥)
/
0 Comments
寫Asp.net很常用到FindControl這個方法,以下為一個自訂的泛型遞迴方法(Generic Recursive Method)。
用意:
透過 FindControl<TextBox>("TextBox1") 找到整個頁面中第一個出現的 TextBox1 控制項(不一定在 Repeater1 裡面)。要使用這段程式比需將以下的程式碼複製到你的頁面的類別(Code behind)中。
public T FindControl<T>(string id)
where T : Control
{
return FindControl<T>(Page, id);
}
public static T FindControl<T>(Control startingControl, stringid)
where T : Control
{
// 取得 T 的預設值,通常是 null T found = default(T);
int controlCount = startingControl.Controls.Count;
if (controlCount > 0)
{
for (int i = 0; i < controlCount; i++)
{
Control activeControl = startingControl.Controls[i];
if (activeControl is T)
{
found = startingControl.Controls[i] as T;
if (string.Compare(id, found.ID, true) == 0)break;
else found = null;
}
else
{
found = FindControl<T>(activeControl, id);
if (found != null) break;
}
}
}
return found;
}