查找一个WebForm控制 [英] Find a control in a webform
问题描述
我有一个Web内容的形式和需要访问该内容面板内的控制。我所知道的访问控制两种方式:
I have a Web content form and need to access a control inside the content panel. I know of two ways to access the control:
-
TXT文本框=(文本框)Page.Controls [0] .Controls [3] .Controls [48] .Controls [6]
- 将编写一个递归函数,通过所有的控制搜索。
有没有其他更简单的方法,因为 Page.FindControl
不会在这种情况下工作。
我问的原因是感觉对我来说,Page对象或内容面板对象应该有发现孩子控制的方法,却找不到这样的事情。
Is there any other easier way, since Page.FindControl
doesn’t work in this instance.
The reason I am asking is it feels to me like the Page object or the Content Panel object should have a method to find a child control, but can’t find anything like it.
推荐答案
的问题是的FindControl()不经过一定的控制的孩子,如模板化控件。如果控制你所追求的生活在一个模板,它不会被发现。
The issue is that FindControl() does not traverse certain control children such as a templated control. If the control you are after lives in a template, it won't be found.
所以我们将以下扩展方法来处理这个问题。如果你不使用3.5或想避免的扩展方法,你可以做一个通用库出这些。
So we added the following extension methods to deal with this. If you are not using 3.5 or want to avoid the extension methods, you could make a general purpose library out of these.
您现在可以得到控制你是后编码:
You can now get the control you are after by coding:
var button = Page.GetControl("MyButton") as Button;
扩展方法为你做递归工作。希望这有助于!
The extension methods do the recursive work for you. Hope this helps!
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();
}
这篇关于查找一个WebForm控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!