最近弄完个项目、项目需要支持多选功能、找了很多例子没找到合适的,最后自己开发了个控件:
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();
}
}

在预呈现 OnPreRender 事件里面注册客户端脚本:
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (!DesignMode)
{
DoRegisterScript();
}
}

重写 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); }
}

在 GetDivWidth 方法里面动态算出 DIV 宽度,避免当某项内容长度超出 DIV 的默认宽度时,动态调整DIV 的宽度。

在 RenderContents 事件里面呈现默认显示(文本框、图标)的内容:
protected override void RenderContents(HtmlTextWriter writer)
{
if (DesignMode)
{
base.RenderContents(writer);
return;
}
RenderCustomContent(writer);
}

在 ModifyRenderedCheckboxes 方法里面呈现 DIV 的内容:

在 LoadPostData 事件里面获取选择的内容:
protected override bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
{
if (!DesignMode)
{
this.txt.Text = postCollection[txt.ID];
this.hfValue.Value = postCollection[hfValue.ID];
this.hfValueText.Value = postCollection[hfValueText.ID];
return true;
}
return base.LoadPostData(postDataKey, postCollection);
}
定义个枚举类型 DisplayMode 表示显示"文本或值"
[Serializable]
public enum DisplayMode
{
/// <summary>
/// 显示文本
/// </summary>
Label,
/// <summary>
/// 显示值
/// </summary>
Value
}
客户端脚本 DropDownCheckBoxList.js 利用 JQuery 来处理:
扩展了 Array :
Array.prototype.initItem
Array.prototype.hasItem
Array.prototype.addItem
Array.prototype.removeItem
Array.prototype.joinItem
函数responseOnFormClick 检测当前点击是否在弹出的DIV 范围;否则隐藏弹出的DIV
function (e, prefix);

函数 toggleDivShowState 显示或者隐藏弹出的DIV

函数 selectDefaultItem 弹出DIV 时设置上次选择的值

控件支持主流浏览器 IE 7+,FF3.5+,Chrome 9+,Safari 5 等浏览器。但在 IE6中与 与浏览器自身的 select 冲突。
转自:http://www.cnblogs.com/xiurui12345/archive/2012/05/03/2480686.html