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

Hca*_*tek 1 c# asp.net ascx findcontrol

我目前在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;
}
Run Code Online (Sandbox Code Playgroud)

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

Joh*_*ers 6

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

只有用户控件才能知道其中的控件.


wom*_*omp 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;
}
Run Code Online (Sandbox Code Playgroud)