c# - 使用 FindControl (""的简单方法)

标签 c# asp.net

C#

你好,

我已经开发 C# Web 应用程序几年了,有一个问题一直困扰着我,我找不到一种合乎逻辑的方法来解决。

我有一个希望在代码后面访问的控件,这个控件在标记的深处;埋藏在 ContentPlaceHolders、UpdatePanels、Panels、GridViews、EmptyDataTemplates、TableCells(或任何您喜欢的结构中。关键是为了正义,它有更多的 parent 而不是更远的人)。

如何在不执行此操作的情况下使用 FindControl("") 访问此控件:

Page.Form.Controls[1].Controls[1].Controls[4].Controls[1].Controls[13].Controls[1].Controls[0].Controls[0].Controls[4].FindControl("");

最佳答案

编写一个名为 FindControlRecursive 的辅助方法,由 Jeff Atwood 自己提供。

private Control FindControlRecursive(Control root, string id) 
{ 
    if (root.ID == id)
    { 
        return root; 
    } 

    foreach (Control c in root.Controls) 
    { 
        Control t = FindControlRecursive(c, id); 
        if (t != null) 
        { 
            return t; 
        } 
    } 

    return null; 
} 

Recursive Page.FindControl

关于c# - 使用 FindControl (""的简单方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2208751/

相关文章:

asp.net - ASP.NET MVC ViewModel模式

c# - ASP.NET - 如何在 C# 表上设置单元格宽度百分比

asp.net - 从 DropDownList 中删除列表项

c# - 正则表达式 - 避免字符

c# - 从 C# 中的 void 方法返回错误消息

c# - mvc.net 动态 url

ASP.Net Azure Web 应用程序身份验证重定向到域而不是本地主机

c# - 使用 where 子句查询 linq

c# - Selectnodes 只获取第一个节点

c# - C# 中的类引用和 GC 循环