最近弄完个项目、项目需要支持多选功能、找了很多例子没找到合适的,最后自己开发了个控件:
DropDownCheckBoxList 控件继承 DropDownList ;
整个控件由四部分组成:一个文本框、两个图标(向下|向上)、一个隐藏的 DIV 、两个隐藏域。控件示意图
收缩状态:
展开状态:
先介绍些关键属性:
1. DisplayMode 有两个值 Label,Value;分别表示显示文本、显示值。
2. Splitor 多选时,多个值间的分隔符。
3. ShowSelectAllOption 是否显示" 全选 " 选项、一般多项选择都会有个" 全选 " 功能。
4. SelectAllOptionLabel 全选选项显示的文本,默认值:"全选"。
重写了 OnInit 事件,在 OnInit 事件里面创建控件:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (!DesignMode)
{
CreateControls();
}
}
1 protected void CreateControls()
2 {
3 txt = new TextBox();
4 txt.ID = this.ClientID + "_txtMain";
5 txt.ReadOnly = true;
6 txt.Width = (Unit)(this.Width.Value - 20);
7 txt.Style.Add(HtmlTextWriterStyle.Padding, "0");
8 txt.Style.Add(HtmlTextWriterStyle.Margin, "0");
9 txt.Height = this.Height;
10
11 if (txt.Height.IsEmpty)
12 { txt.Height = 15; }
13
14 hfValueText = new HiddenField();
15 hfValueText.ID = string.Format("{0}_{1}", this.ClientID, "selectItemValueText");
16 hfValue = new HiddenField();
17 hfValue.ID = string.Format("{0}_{1}", this.ClientID, "selectItemValue");
18
19 txt.Enabled = this.Enabled;
20 }
在预呈现 OnPreRender 事件里面注册客户端脚本:
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (!DesignMode)
{
DoRegisterScript();
}
}
1 ClientScriptManager sc = this.Page.Page.ClientScript;
2
3 string scriptString = sc.GetWebResourceUrl(this.GetType(), "DevControl.Resources.DropDownCheckBoxList.js");
4
5 if (!sc.IsClientScriptIncludeRegistered("DropDownGridScriptKey"))
6 { sc.RegisterClientScriptInclude(this.GetType(), "DropDownGridScriptKey", scriptString); }
7
8 scriptString = Page.Form.Attributes["onclick"];
9 if (string.IsNullOrEmpty(scriptString))
10 { scriptString = string.Format("responseOnFormClick(event,'{0}');", this.ClientID); }
11 else
12 { scriptString = string.Format("{0} responseOnFormClick(event,'{1}');", scriptString, this.ClientID); }
13
14 Page.Form.Attributes.Add("onclick", scriptString);
15
16 this.Page.RegisterRequiresPostBack(this);
重写 TagKey 设置为:Table
protected override HtmlTextWriterTag TagKey
{
get
{
if (!DesignMode)
{
return HtmlTextWriterTag.Table;
}
return base.TagKey;
}
}
在 AddAttributesToRender 事件中 设置 table 的属性
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
if (!DesignMode)
{ AddCustomAttribute(writer); }
else
{ base.AddAttributesToRender(writer); }
}
1 writer.AddAttribute(HtmlTextWriterAttribute.Width, this.Width.ToString());
2 writer.AddAttribute(HtmlTextWriterAttribute.Border, "0");
3 writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID + "_displaytable");
4 writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "0");
5 writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0");
6 writer.AddStyleAttribute(HtmlTextWriterStyle.Position, "relative");
7 writer.AddStyleAttri