Moh*_*med 21 c# webforms asp.net-controls
我在页面中有多个下拉列表,如果用户选择一个禁用全部的复选框,则要禁用所有.到目前为止,我有这个代码,它无法正常工作.有什么建议?
foreach (Control c in this.Page.Controls)
{
if (c is DropDownList)
((DropDownList)(c)).Enabled = false;
}
Run Code Online (Sandbox Code Playgroud)
Joh*_*han 38
每个控件都有子控件,因此您需要使用递归来实现所有控件:
protected void DisableControls(Control parent, bool State) {
foreach(Control c in parent.Controls) {
if (c is DropDownList) {
((DropDownList)(c)).Enabled = State;
}
DisableControls(c, State);
}
}
Run Code Online (Sandbox Code Playgroud)
然后像这样调用它:
protected void Event_Name(...) {
DisableControls(Page,false); // use whatever top-most control has all the dropdowns or just the page control
} // divs, tables etc. can be called through adding runat="server" property
Run Code Online (Sandbox Code Playgroud)
Jus*_*rke 29
我知道这是一个老帖子,但这就是我刚刚解决了这个问题的方法.根据标题"我如何禁用ASP.NET页面中的所有控件?" 我用反射来达到这个目的; 它适用于具有Enabled属性的所有控件类型.只需调用传入父控件(即表单)的DisableControls即可.
C#:
private void DisableControls(System.Web.UI.Control control)
{
foreach (System.Web.UI.Control c in control.Controls)
{
// Get the Enabled property by reflection.
Type type = c.GetType();
PropertyInfo prop = type.GetProperty("Enabled");
// Set it to False to disable the control.
if (prop != null)
{
prop.SetValue(c, false, null);
}
// Recurse into child controls.
if (c.Controls.Count > 0)
{
this.DisableControls(c);
}
}
}
Run Code Online (Sandbox Code Playgroud)
VB:
Private Sub DisableControls(control As System.Web.UI.Control)
For Each c As System.Web.UI.Control In control.Controls
' Get the Enabled property by reflection.
Dim type As Type = c.GetType
Dim prop As PropertyInfo = type.GetProperty("Enabled")
' Set it to False to disable the control.
If Not prop Is Nothing Then
prop.SetValue(c, False, Nothing)
End If
' Recurse into child controls.
If c.Controls.Count > 0 Then
Me.DisableControls(c)
End If
Next
End Sub
Run Code Online (Sandbox Code Playgroud)
小智 8
在要禁用的页面部分周围放置一个面板:
< asp:Panel ID="pnlPage" runat="server" >
...
< /asp:Panel >
Run Code Online (Sandbox Code Playgroud)
在Page_Load里面:
If Not Me.Page.IsPostBack Then
Me.pnlPage.Enabled = False
End If
Run Code Online (Sandbox Code Playgroud)
......或C#等价物.:O)