自定义控件之多选下拉框

1、控件代码:

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Web.UI.HtmlControls;
using System.Drawing;
namespace My.Controls
{
    [Serializable]
    public class DropDownCheckBoxList : DropDownList
    {
        #region 属性
        /// <summary>
        /// 多选分隔符 默认为 " , "
        /// </summary>
        [DefaultValue(",")]
        [Browsable(true)]
        [Category("property")]
        public string Splitor
        {
            get
            {
                return ViewState["Splitor"] == null ? "," : ViewState["Splitor"].ToString();
            }
            set { ViewState["Splitor"] = value; }
        }

        /// <summary>
        /// 选择的文本
        /// </summary>
        [DefaultValue("")]
        [Browsable(true)]
        public string SelectedText
        {
            get
            {
                return this.txt.Text;
            }
            set
            {
                this.txt.Text = value;
            }
        }

        /// <summary>
        /// 选择的值
        /// </summary>
        [DefaultValue("")]
        [Browsable(true)]
        public override string SelectedValue
        {
            get
            {
                return hfValue.Value;
            }
            set
            {
                hfValue.Value = value;
            }
        }

        /// <summary>
        /// 选择的值|文本
        /// </summary>
        [DefaultValue("")]
        [Browsable(true)]
        public string SelectedValueAndText
        {
            get
            {
                return this.hfValueText.Value;
            }
            set
            {
                this.hfValueText.Value = value;
            }
        }

        /// <summary>
        /// 是否自动显示"全选"选项
        /// </summary>
        [DefaultValue(false)]
        [Browsable(true)]
        public bool ShowSelectAllOption
        {
            get
            {
                return ViewState["ShowSelectAllOption"] == null ? false : (bool)ViewState["ShowSelectAllOption"];
            }
            set { ViewState["ShowSelectAllOption"] = value; }
        }

        TextBox txt = null;
        HiddenField hfValue = null;
        HiddenField hfValueText = null;
        HtmlInputButton btn = null;
        #endregion

        protected override void OnInit(EventArgs e)
        {
            CreateControls();
            base.OnInit(e);
        }

        protected override void OnPreRender(EventArgs e)
        {
            DoRegisterScript();
            base.OnPreRender(e);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            RenderCustomContent(writer);
        }


        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            AddCustomAttribute(writer);
        }

        public override void RenderBeginTag(HtmlTextWriter writer)
        {
            AddAttributesToRender(writer);
            writer.RenderBeginTag(HtmlTextWriterTag.Div);
        }

        public override void RenderEndTag(HtmlTextWriter writer)
        {
            base.RenderEndTag(writer);
        }

        protected override bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
        {
            this.txt.Text = postCollection[txt.ID];
            this.hfValue.Value = postCollection[hfValue.ID];
            this.hfValueText.Value = postCollection[hfValueText.ID];
            return true;
        }

        private void AddCustomAttribute(HtmlTextWriter writer)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Width, this.Width.ToString());
            writer.AddAttribute(HtmlTextWriterAttribute.Height, this.Height.ToString());
            writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID + "_div_t");
            writer.AddStyleAttribute(HtmlTextWriterStyle.Position, "relative");
            writer.AddStyleAttribute(HtmlTextWriterStyle.Padding, "0");
            writer.AddStyleAttribute(HtmlTextWriterStyle.Margin, "0");
        }

        private void CreateControls()
        {
            txt = new TextBox();
            txt.ID = this.ClientID + "_txtMain";
            txt.ReadOnly = true;
            if (this.Width.IsEmpty)
            {
                this.Width = 120;
            }
            if (this.Height.IsEmpty)
            {
                this.Height = 20;
            }
            txt.Width = (Unit)(this.Width.Value - 20);
            txt.Style.Add(HtmlTextWriterStyle.Padding, "0");
            txt.Style.Add(HtmlTextWriterStyle.Margin, "0");
            txt.Height = this.Height;

            hfValueText = new HiddenField();
            hfValueText.ID = string.Format("{0}_{1}", this.ClientID, "selectItemValueText");
            hfValue = new HiddenField();
            hfValue.ID = string.Format("{0}_{1}", this.ClientID, "selectItemValue");

            txt.Enabled = this.Enabled;

            btn = new HtmlInputButton();
            btn.Value = "";
            btn.ID = string.Format("{0}_{1}", this.ClientID, "button");
            btn.Style.Add(HtmlTextWriterStyle.Width, "20");
            btn.Style.Add(HtmlTextWriterStyle.Height, this.Height.ToString());
            if (this.Enabled)
            {
                btn.Attributes.Add("onclick", string.Format("{0}Object.ShowDiv()", this.ClientID));
            }
        }

        private void DoRegisterScript()
        {
            if (this.Page != null)
            {
                this.Page.RegisterRequiresPostBack(this);

                StringBuilder builder = new StringBuilder();
                builder.Append("<script type=\"text/javascript\">");
                builder.Append("var DropDownCheckBoxClass = function() {");
                builder.Append(string.Format("var div = document.getElementById('{0}_div');", this.ClientID));
                builder.Append("this.ShowDiv = function() { $(div).toggle(); };");
                builder.Append("this.SelAll = function(obj,tab) { var objs = $('#' + tab + '  input[type=\"checkbox\"]');");
                builder.Append("var ids='';var name=''; objs.attr('checked',obj.checked);");
                builder.Append("if(obj.checked){ objs.each(function(i,j){if(j.value.length>0){ids+=j.value+'");
                builder.Append(Splitor);
                builder.Append("';name+=j.ref_name+'");
                builder.Append(Splitor);
                builder.Append("'}});}$('#");
                builder.Append(hfValue.ID);
                builder.Append("').val(ids);$('#");
                builder.Append(txt.ID);
                builder.Append("').val(name) };");
                builder.Append("\r\n");

                builder.Append("this.SelOne = function(obj,tab) { var objs = $('#' + tab + '  input[type=\"checkbox\"][@checked]');");
                builder.Append("var ids='';var name=''; ");
                builder.Append("objs.each(function(i,j){if(j.value.length>0){ids+=j.value+'");
                builder.Append(Splitor);
                builder.Append("';name+=j.ref_name+'");
                builder.Append(Splitor);
                builder.Append("';}});$('#");
                builder.Append(hfValue.ID);
                builder.Append("').val(ids);$('#");
                builder.Append(txt.ID);
                builder.Append("').val(name); };");

                builder.Append("} \r\n");
                builder.Append(string.Format("var {0}Object = new DropDownCheckBoxClass();</script>", this.ClientID));

                string scriptBody = builder.ToString();
                this.Page.ClientScript.RegisterStartupScript(typeof(string), this.ClientID, scriptBody);
            }

        }

        private void GetDivWidth()
        {
            int itemWidth = 0;
            int byteCount = 0;
            foreach (ListItem item in this.Items)
            {
                byteCount = System.Text.UnicodeEncoding.Default.GetByteCount(item.Text);
                if (byteCount > itemWidth)
                { itemWidth = byteCount; }
            }

            itemWidth = itemWidth * 8 + 20;
            itemWidth = itemWidth + 16; //加上checkbox 宽度

            if (itemWidth > this.Width.Value)
            { this.Width = itemWidth; }
        }

        private void RenderCustomContent(HtmlTextWriter writer)
        {
            GetDivWidth();
            string divId = this.ClientID + "_div";

            AddAttributesToRender(writer);
            ////控件显示主体
            writer.RenderBeginTag(HtmlTextWriterTag.Div);//begin

            writer.AddAttribute(HtmlTextWriterAttribute.Align, "left");
            writer.AddStyleAttribute(HtmlTextWriterStyle.Cursor, "default");

            ////控件主体文本框 
            txt.RenderControl(writer);
            btn.RenderControl(writer);

            ////隐藏下拉面板
            writer.AddAttribute(HtmlTextWriterAttribute.Id, divId);
            writer.AddStyleAttribute(HtmlTextWriterStyle.Display, "none");
            writer.AddStyleAttribute(HtmlTextWriterStyle.BackgroundColor, "#AFDEFF");
            writer.AddStyleAttribute(HtmlTextWriterStyle.Position, "absolute");
            writer.AddStyleAttribute(HtmlTextWriterStyle.ZIndex, "32766");
            writer.AddStyleAttribute(HtmlTextWriterStyle.BorderColor, "Gray");
            writer.AddStyleAttribute(HtmlTextWriterStyle.BorderWidth, "thin");
            writer.AddStyleAttribute(HtmlTextWriterStyle.BorderStyle, "double");
            writer.AddStyleAttribute(HtmlTextWriterStyle.VerticalAlign, "top");
            writer.AddStyleAttribute(HtmlTextWriterStyle.Width, this.Width.ToString());
            writer.AddStyleAttribute(HtmlTextWriterStyle.Top, this.Height.ToString());
            writer.AddStyleAttribute(HtmlTextWriterStyle.Left, "0");
            writer.RenderBeginTag(HtmlTextWriterTag.Div);//begin
            ////呈现 item 列表
            ModifyRenderedCheckboxes(writer);
            writer.RenderEndTag();//end div
            writer.RenderEndTag();//end div

        }

        private void ModifyRenderedCheckboxes(HtmlTextWriter writer)
        {
            int index = 0;

            string spanId = "";
            string wapperId = "";
            string allChkId = "";
            string tableId = this.ClientID + "_Optiontable";
            writer.AddAttribute(HtmlTextWriterAttribute.Width, this.Width.ToString());
            writer.AddAttribute(HtmlTextWriterAttribute.Border, "0");
            writer.AddAttribute(HtmlTextWriterAttribute.Id, tableId);
            writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "0");
            writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0");
            writer.AddStyleAttribute(HtmlTextWriterStyle.Position, "relative");
            writer.AddStyleAttribute(HtmlTextWriterStyle.Left, "0px");
            writer.RenderBeginTag(HtmlTextWriterTag.Table);//begin

            #region 首选项
            if (ShowSelectAllOption)
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Tr);//begin
                wapperId = string.Format("{0}_{1}", this.ClientID, "chkAllItemWapper");
                allChkId = string.Format("{0}_{1}", this.ClientID, "chkAllItemValue");
                spanId = string.Format("{0}_{1}", this.ClientID, "chkAllItemText");

                writer.AddStyleAttribute(HtmlTextWriterStyle.Width, (this.Width.Value - 10).ToString());
                writer.AddStyleAttribute(HtmlTextWriterStyle.Height, "20px");
                writer.AddAttribute(HtmlTextWriterAttribute.Id, wapperId);
                writer.AddStyleAttribute("cursor", "pointer");
                writer.AddStyleAttribute("cursor", "hand");
                writer.AddStyleAttribute(HtmlTextWriterStyle.VerticalAlign, "middle");
                writer.AddStyleAttribute(HtmlTextWriterStyle.PaddingLeft, "5px");
                writer.AddStyleAttribute(HtmlTextWriterStyle.PaddingRight, "5px");
                writer.RenderBeginTag(HtmlTextWriterTag.Td);//begin

                writer.AddAttribute(HtmlTextWriterAttribute.Id, allChkId);
                writer.AddAttribute(HtmlTextWriterAttribute.Onclick, string.Format("{0}Object.SelAll(this,'{1}')", this.ClientID, tableId));
                writer.AddStyleAttribute("cursor", "pointer");
                writer.AddStyleAttribute("cursor", "hand");
                writer.AddAttribute(HtmlTextWriterAttribute.Value, "");
                writer.AddStyleAttribute(HtmlTextWriterStyle.VerticalAlign, "middle");
                writer.AddStyleAttribute(HtmlTextWriterStyle.PaddingBottom, "5px");
                writer.AddAttribute(HtmlTextWriterAttribute.Type, "checkbox");
                writer.RenderBeginTag(HtmlTextWriterTag.Input);//begin
                writer.RenderEndTag();//end input

                writer.AddAttribute(HtmlTextWriterAttribute.Id, spanId);
                writer.AddStyleAttribute(HtmlTextWriterStyle.FontSize, "small");
                writer.AddStyleAttribute(HtmlTextWriterStyle.PaddingTop, "5px");
                writer.AddStyleAttribute(HtmlTextWriterStyle.VerticalAlign, "middle");
                writer.AddStyleAttribute(HtmlTextWriterStyle.PaddingBottom, "5px");
                writer.RenderBeginTag(HtmlTextWriterTag.Span);//begin
                writer.RenderEndTag();//end span
                writer.Write("全选");

                writer.RenderEndTag();//td

                writer.RenderEndTag();//tr
            }
            #endregion

            #region 内容选项
            string chkId = "";
            foreach (ListItem item in this.Items)
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Tr);//begin
                wapperId = string.Format("{0}_{1}{2}", this.ClientID, "chkItemWapper", index.ToString());
                chkId = string.Format("{0}_{1}{2}", this.ClientID, "chkItemValue", index.ToString());
                spanId = string.Format("{0}_{1}{2}", this.ClientID, "chkItemText", index.ToString());

                //writer.AddAttribute("onmouseover", string.Format("setStyleOnMouseOver('{0}');", wapperId));
                //writer.AddAttribute("onmouseout", string.Format("setStyleOnMouseOut('{0}');", wapperId));

                writer.AddStyleAttribute(HtmlTextWriterStyle.Width, (this.Width.Value - 10).ToString());
                writer.AddStyleAttribute(HtmlTextWriterStyle.Height, "20px");
                writer.AddAttribute(HtmlTextWriterAttribute.Id, wapperId);
                writer.AddStyleAttribute("cursor", "pointer");
                writer.AddStyleAttribute("cursor", "hand");
                writer.AddStyleAttribute(HtmlTextWriterStyle.VerticalAlign, "middle");
                writer.AddStyleAttribute(HtmlTextWriterStyle.PaddingLeft, "5px");
                writer.AddStyleAttribute(HtmlTextWriterStyle.PaddingRight, "5px");
                writer.RenderBeginTag(HtmlTextWriterTag.Td);//begin

                writer.AddAttribute(HtmlTextWriterAttribute.Id, chkId);
                writer.AddAttribute(HtmlTextWriterAttribute.Onclick, string.Format("{0}Object.SelOne(this,'{1}')", this.ClientID, tableId));
                writer.AddStyleAttribute("cursor", "pointer");
                writer.AddStyleAttribute("cursor", "hand");
                writer.AddStyleAttribute(HtmlTextWriterStyle.PaddingTop, "5px");
                writer.AddStyleAttribute(HtmlTextWriterStyle.VerticalAlign, "middle");
                writer.AddStyleAttribute(HtmlTextWriterStyle.PaddingBottom, "5px");
                writer.AddAttribute(HtmlTextWriterAttribute.Width, "16px");
                writer.AddAttribute(HtmlTextWriterAttribute.Value, item.Value);
               // writer.AddAttribute(HtmlTextWriterAttribute.Onclick, string.Format("return mouseUpdateValueWhenCheckItemStateChanged(event,'{0}','{1}','{2}','{3}');", chkId, spanId, allChkId, this.ClientID));
                writer.AddAttribute(HtmlTextWriterAttribute.Type, "checkbox");
                writer.AddAttribute("ref_name", item.Text);
                writer.RenderBeginTag(HtmlTextWriterTag.Input);//begin
                writer.RenderEndTag();//end input

                writer.AddAttribute(HtmlTextWriterAttribute.Id, spanId);
                writer.AddStyleAttribute(HtmlTextWriterStyle.FontSize, "small");
                writer.AddStyleAttribute(HtmlTextWriterStyle.PaddingTop, "5px");
                writer.AddStyleAttribute(HtmlTextWriterStyle.VerticalAlign, "middle");
                writer.AddStyleAttribute(HtmlTextWriterStyle.PaddingBottom, "5px");
                writer.RenderBeginTag(HtmlTextWriterTag.Span);//begin
                writer.Write(item.Text);
                writer.RenderEndTag();//end span

                writer.RenderEndTag();//td
                writer.RenderEndTag();//tr
                index++;
            }
            #endregion

            writer.RenderBeginTag(HtmlTextWriterTag.Tr);//begin
            writer.RenderBeginTag(HtmlTextWriterTag.Td);//begin
            hfValue.RenderControl(writer);
            hfValueText.RenderControl(writer);
            writer.RenderEndTag();//end td
            writer.RenderEndTag();//end tr
            writer.RenderEndTag();//end table
        }

    }
}

 2.在web.config中注册:

<system.web>

   <controls>
        <add tagPrefix="mycontrol" assembly=".........." namespace=".........." />
      </controls>

</system.web>

3.页面中使用:<mycontrol:DropDownCheckBoxList ID="drpcarType" runat="Server" ShowSelectAllOption="true">

4.效果图:

 

posted @ 2015-01-26 18:09  FancyYOYO  阅读(254)  评论(0编辑  收藏  举报