【问题标题】:How to get a reference to a control from its' string name in C#如何从 C# 中的字符串名称中获取对控件的引用
【发布时间】:2009-01-30 04:27:54
【问题描述】:

如何从 C# 中的字符串名称中获取对控件的引用?

【问题讨论】:

    标签: c# asp.net visual-studio controls visual-web-developer


    【解决方案1】:

    Page.FindControl

    如果控件是嵌套的,请使用父控件中的Control.FindControl。否则,您必须自己编写FindControlRecursive

    【讨论】:

    • 注意:在控件集合中,FindControl 方法将返回同名控件的不同实例。在 ASP.NET 中,该控件也将具有唯一的名称。换句话说,FindControlRecursive 将返回该名称的第一个控件。
    【解决方案2】:
            private Control FindControlRecursive(Control root, string id)
            {
                return root.ID == id
                           ? root
                           : (root.Controls.Cast<Control>()
                                 .Select(c => FindControlRecursive(c, id)))
                                 .FirstOrDefault(t => t != null);
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-22
      • 2021-08-31
      • 1970-01-01
      • 1970-01-01
      • 2018-10-30
      • 1970-01-01
      • 2016-05-15
      • 2011-08-04
      相关资源
      最近更新 更多