循环通过控件ASP.NET



我正在尝试制作一个函数以禁用特定页面中的所有控件。

当我循环循环时,所有控件将被禁用,除了设置为runat =" server"

的DIV内部的控件

这是设计的一般视图:

<form id="form1" runat="server">
   <div id="wrapper">
   <%-- 1st set of ASP controls --%>
      <div id="Main" runat="server">
         <%-- 2nd set ASP of controls --%>
      </div>
   </div>
<form>

我的代码看起来像这样:

For Each c As Control In Page.Controls
   For Each ctrl As Control In c.Controls
      'disabling controls 
   Next
Next

我想在我的所有页面中使用此功能,请让我知道如何循环循环通过runat =" server"?

您想做的是禁用/启用页面子女的控件,也是控制页面的子女的控件。为此,您需要使用递归功能。类似:

private void DisableChildControls(ControlCollection controls, int depthLimit)
{
   if(depthLimit <= 0)
      return;
   foreach(var ctl in controls)
   {
      ctl.Enabled = false;
      if(ctl.Controls.Count > 0)
      {
         DisableChildControls(ctl.Controls, --depthLimit);
      }
    }
}

在页面加载事件中,您调用:

开始启动遍历
if(this.Controls.Count > 0)
   DisableChildControls(this.Controls, 2); //If you want the depth to be two levels.

这将递归地禁用在树下,直到您指定的极限。只需考虑到一个复杂的页面,此递归操作可能需要大量时间。

还要注意,无论好坏,这只会通过用runat="server"

标记的控件循环。

最新更新