1

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

4

2 回答 2

6

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

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

于 2009-12-31T23:04:38.247 回答
6

通常,当您有很多控件查找要做时,我会实现“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;
}
于 2009-12-31T23:06:07.823 回答