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

发布于 2024-08-16 08:16:49 字数 424 浏览 2 评论 0原文

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

I currently have a dropdown inside an ascx control. I need to "find" it from within the code behind on another ascx that is on the same page. It's value is used as a param to an ObjectDataSource on ascx #2. I am currently using this ugly piece of code. It works but I realize if the conrtol order were to change or various other things, it wouldn't be where I am expecting. Does anyone have any advice how I should properly be doing this?

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

Thanks and Happy New Year!!
~ck in San Diego

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心清如水 2024-08-23 08:16:49

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

Generally I implement a "FindInPage" or recursive FindControl function when you have lots of control finding to do, where you would just pass it a control and it would recursively descend the control tree.

If it's just a one-off thing, consider exposing the control you need in your API so you can access it directly.

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;
}
别把无礼当个性 2024-08-23 08:16:49

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

只有用户控件应该知道其内部有哪些控件。

Expose a property on the user control class which will return the value you need. Let the page access the property.

Only the user control should know what controls are inside of it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文