【问题标题】:ASP.NET Is there a better way to find controls that are within other controls?ASP.NET 是否有更好的方法来查找其他控件中的控件?
【发布时间】:2010-12-31 12:57:20
【问题描述】:

我目前在 ascx 控件中有一个下拉菜单。我需要从同一页面上另一个 ascx 后面的代码中“找到”它。它的值用作 ascx #2 上的 ObjectDataSource 的参数。我目前正在使用这段丑陋的代码。它有效,但我意识到如果控制命令发生变化或其他各种事情,它不会是我所期望的。有人对我应该如何正确执行此操作有任何建议吗?

if(Page is ClaimBase)
{
  var p = Page as ClaimBase;
  var controls = p.Controls[0].Controls[3].Controls[2].Controls[7].Controls[0];
  var ddl = controls.FindControl("ddCovCert") as DropDownList;
}

谢谢,新年快乐!! ~ck 在圣地亚哥

【问题讨论】:

    标签: c# asp.net ascx findcontrol


    【解决方案1】:

    通常,当您需要查找大量控件时,我会实现“FindInPage”或递归 FindControl 函数,您只需将控件传递给它,然后它会递归地下降控件树。

    如果这只是一次性的事情,请考虑在 API 中公开您需要的控件,以便您可以直接访问它。

    public static Control DeepFindControl(Control c, string id)
    {
       if (c.ID == id)
       { 
         return c;
       }
       if (c.HasControls)
       {
          Control temp;
          foreach (var subcontrol in c.Controls)
          {
              temp = DeepFindControl(subcontrol, id);
              if (temp != null)
              {
                  return temp; 
              }
          }
       }
       return null;
    }
    

    【讨论】:

    • 甜蜜。我经常使用它,而且效果很好。一个简单的解决方案。
    【解决方案2】:

    在用户控件类上公开一个属性,该属性将返回您需要的值。让页面访问该属性。

    只有用户控件应该知道里面有什么控件。

    【讨论】:

      猜你喜欢
      • 2011-06-24
      • 1970-01-01
      • 2012-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-15
      • 2016-11-24
      • 2011-03-10
      相关资源
      最近更新 更多