c# - 在网络表单中查找控件

标签 c# asp.net webforms

我有一个 Web 内容表单,需要访问内容面板内的控件。我知道有两种访问控件的方法:

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

有没有其他更简单的方法,因为 Page.FindControl 在这种情况下不起作用。 我问的原因是我觉得 Page 对象或 Content Panel 对象应该有一个方法来查找子控件,但找不到类似的方法。

最佳答案

问题是 FindControl() 不会遍历某些子控件,例如模板控件。如果您要查找的控件存在于模板中,则不会找到它。

所以我们添加了以下扩展方法来处理这个问题。如果您不使用 3.5 或不想使用扩展方法,则可以使用这些方法制作一个通用库。

您现在可以通过编码获得您想要的控件:

var button = Page.GetControl("MyButton") as Button;

扩展方法为您完成递归工作。希望这对您有所帮助!

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();
}

关于c# - 在网络表单中查找控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/619449/

相关文章:

c# - 获取在 RadGrid 中触发 ItemCommand 的控件的 ID

c# - ASP NET session 使用 .ToString() 抛出错误

c# - 为什么 SendBatch 从事件中心 .NET Standard 客户端中删除?有替代品吗?

c# - ASP.NET 和 C# : hide spinning wheel when button has finished processing

c# typeof 应用于泛型参数父类(super class)型

c# - BulletedList onClick 未触发

jquery - youtube 自定义标题的 Fancybox 无法正常显示

c# - 是否可以在运行时在不同的 Winform 项目上使用不同的配置文件?

asp.net - RESTful 验证密码服务

c# - 将值设置为隐藏输入