最近在一个winform项目中碰到的一个功能,勾选一个checkbox后窗体中的其他控件不可用。由此想到asp.net项目中有时候也要用到这种功能。
using来源gaodai#ma#com搞@@代~&码网 System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
namespace DotNet.Common.Util
{
///
///
public enum ControlNameEnum
{
Panel = 0, //容器 这个比较常用
TextBox = 1,
Button = 2, //这个也比较常用 比如 按钮提交后的禁用,返回结果后启用
CheckBox = 3,
ListControl = 4,
All = 100 //所有
}
public static class ControlHelper
{
#region 同时禁用或者启用页面的某些控件
///
///
///
///
///
public static void SetControlsEnabled(Control control, ControlNameEnum controlName, bool isEnabled)
{
foreach (Control item in control.Controls)
{
/* 我们仅仅考虑几种常用的asp.net服务器控件和html控件 */
//Panel
if (item is Panel && (controlName == ControlNameEnum.Panel || controlName == ControlNameEnum.All))
{
((Panel)item).Enabled = isEnabled;
}
//TextBox,HtmlTextBox
if (controlName == ControlNameEnum.TextBox || controlName == ControlNameEnum.All)
{
if (item is TextBox)
{
((TextBox)(item)).Enabled = isEnabled;
}
else if (item is HtmlInputText)
{
((HtmlInputText)item).Disabled = isEnabled;
}
else if (item is HtmlTextArea)
{
((HtmlTextArea)(item)).Disabled = isEnabled;
}
}
//Buttons
if (item is Button && (controlName == ControlNameEnum.Button || controlName == ControlNameEnum.All))
{
if (item is Button)
{
((Button)(item)).Enabled = isEnabled;
}
else if (item is HtmlInputButton)
{
((HtmlInputButton)(item)).Disabled = !isEnabled;
}
else if (item is ImageButton)
{
((ImageButton)(item)).Enabled = isEnabled;
}
else if (item is LinkButton)
{
((LinkButton)(item)).Enabled = isEnabled;
}
}
//CheckBox
if (controlName == ControlNameEnum.CheckBox || controlName == ControlNameEnum.All)
{
if (item is CheckBox)
{
((CheckBox)(item)).Enabled = isEnabled;
}
else if (item is HtmlInputCheckBox)
{
((HtmlInputCheckBox)(item)).Disabled = !isEnabled;
}
}
//List Controls
if (controlName == ControlNameEnum.ListControl || controlName == ControlNameEnum.All)
{
if (item is DropDownList)
{
((DropDownList)(item)).Enabled = isEnabled;
}
else if (item is RadioButtonList)
{
((RadioButtonList)(item)).Enabled = isEnabled;
}
else if (item is CheckBoxList)
{
((CheckBoxList)(item)).Enabled = isEnabled;
}
else if (item is ListBox)
{
((ListBox)(item)).Enabled = isEnabled;
}
else if (item is HtmlSelect)
{
((HtmlSelect)(item)).Disabled = !isEnabled;
}
}
//如果项目还有子控件,递归调用该函数
if (item.Controls.Count > 0)
{
SetControlsEnabled(item, controlName, isEnabled);
}
}
}
#endregion
}
}
在aspx页面中的调用如下:
{
if (!IsPostBack)
{
ControlHelper.SetControlsEnabled(this.Page, ControlNameEnum.Panel, false); //Panel禁用
}
}
需要注意的是,我这里的实现只是针对几种常用控件,您可以按照自己项目的需要任意扩展。
测试打包下载
以上就是asp.net 简单实现禁用或启用页面中的某一类型的控件的详细内容,更多请关注gaodaima搞代码网其它相关文章!