我有多个下拉列表在一个页面上,并想禁用所有,如果用户选择了一个复选框,这是禁用所有。到目前为止,我有这段代码,但它不能工作。有什么建议吗?
foreach (Control c in this.Page.Controls)
{
if (c is DropDownList)
((DropDownList)(c)).Enabled = false;
}
发布于 2009-02-02 23:10:44
每个控件都有子控件,因此您需要使用递归来访问所有控件:
protected void DisableControls(Control parent, bool State) {
foreach(Control c in parent.Controls) {
if (c is DropDownList) {
((DropDownList)(c)).Enabled = State;
}
DisableControls(c, State);
}
}
然后这样叫它:
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
发布于 2013-04-09 23:15:49
我知道这是一个古老的帖子,但这是我刚刚解决这个问题的方法。按照标题“如何禁用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);
}
}
}
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
发布于 2009-02-02 23:04:22
如果您将所有要禁用的控件放在一个面板中,然后只启用/禁用该面板,这将是最简单的。
https://stackoverflow.com/questions/505353
复制相似问题