Vấn đề là FindControl() không đi qua một số trẻ điều khiển nhất định chẳng hạn như điều khiển khuôn mẫu. Nếu kiểm soát bạn sau khi sống trong một mẫu, nó sẽ không được tìm thấy.
Vì vậy, chúng tôi đã thêm các phương pháp mở rộng sau đây để giải quyết vấn đề này. Nếu bạn không sử dụng 3.5 hoặc muốn tránh các phương pháp mở rộng, bạn có thể làm cho một thư viện mục đích chung trong số này.
Bây giờ bạn có thể nhận được sự kiểm soát bạn bằng cách mã hóa sau:
var button = Page.GetControl("MyButton") as Button;
phương pháp Phần mở rộng làm công việc đệ quy cho bạn. Hi vọng điêu nay co ich!
public static IEnumerable<Control> Flatten(this ControlCollection controls)
{
List<Control> list = new List<Control>();
controls.Traverse(c => list.Add(c));
return list;
}
public static IEnumerable<Control> Flatten(this ControlCollection controls,
Func<Control, bool> predicate)
{
List<Control> list = new List<Control>();
controls.Traverse(c => { if (predicate(c)) list.Add(c); });
return list;
}
public static void Traverse(this ControlCollection controls, Action<Control> action)
{
foreach (Control control in controls)
{
action(control);
if (control.HasControls())
{
control.Controls.Traverse(action);
}
}
}
public static Control GetControl(this Control control, string id)
{
return control.Controls.Flatten(c => c.ID == id).SingleOrDefault();
}
public static IEnumerable<Control> GetControls(this Control control)
{
return control.Controls.Flatten();
}
Ồ, đây sẽ là p nghệ thuật của Framework! – Marcel