繁体   English   中英

ASP.NET是否有更好的方法来查找其他控件中的控件?

[英]ASP.NET Is there a better way to find controls that are within other controls?

我目前在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在圣地亚哥

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

只有用户控件应该知道其中包含哪些控件。

通常,当您有很多控件要查找时,我会实现“ 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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM