繁体   English   中英

循环控制asp.net

[英]Loop through controls asp.net

我正在尝试创建一个功能来禁用特定页面中的所有控件。

循环时,除了div中设置为runat =“server”的控件外,所有控件都被禁用

这是设计的一般视图:

<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”的div?

您要做的是禁用/启用作为页面子项的控件,以及作为页面子项的控件的子控件。 为此,您需要使用递归函数。 就像是:

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"控件

暂无
暂无

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

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