在网络表单中查找控件 [英] Find a control in a webform

查看:39
本文介绍了在网络表单中查找控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 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:

  1. TextBox txt = (TextBox)Page.Controls[0].Controls[3].Controls[48].Controls[6]
  2. 编写一个递归函数来搜索所有控件.

有没有其他更简单的方法,因为 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();
}

这篇关于在网络表单中查找控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆