自定义控件之多选下拉框_ddrhv37753的博客-程序员ITS203

技术标签: ViewUI  ui  javascript  

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.效果图:

 

转载于:https://www.cnblogs.com/fanyit123/p/4250971.html

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/ddrhv37753/article/details/101397220

智能推荐

Gephi绘制网络图初步探索_Candle_light的博客-程序员ITS203_gephi网络图

文章目录1. Gephi 基本功能简介1.1 数据输入格式1.2 Gephi界面初探1.3 数据导入2. 设置节点的属性2.1 设置节点颜色2.2 设置节点大小2.3 设置布局2.4 关于边的属性3. 图的设置4. 预览(preview)5. 导出6. 参考链接1. Gephi 基本功能简介近期因为要绘制特效基因网络图,所以开始学习Gephi, Gephi是一款功能很强大的网络绘制软件,对于...

vivado hls 对数组、for循环处理_weixin_41967965的博客-程序员ITS203_vivado 数组

数组 可以通过resource关键字来决定数组实现方式 可以通过分块、寄存器等方式多维数组: 1、数组的实现数组通常会被综合为memory(RAM,ROM,或者FIFO)。Top-level function中的数组会被综合为RTL ports,与外部的memory进行access。这个在数组的接口中会讨论。 内部的数组会被综合为RAM,LUTRA...

Flask 学习-19.配置管理flask_sqlalchemy 和 flask_migrate_上海-悠悠的博客-程序员ITS203_db = sqlalchemy(app)

前面讲了项目中使用config.py 可以管理开发、生产、测试等环境的配置,这篇继续学习在项目中添加flask_sqlalchemy 和 flask_migrate 的配置

解压并安装Hadoop2.7.1_残@ 歌的博客-程序员ITS203_hadoop-2.7.1.tar.gz

一、解压并安装Hadoop2.7.11、解压hadoop(主节点)$ sudo tar -zxvf hadoop-2.7.1.tar.gz -C /usr/local解压hadoop2.7.1.tar.gz文件,文件位置根据情况而定,本机文件正好放在根目录下,所以没有带路径,请一定根据自己文件所在路径把相应路径加上,进行解压,/usr/local为目标路径,也是根据情况而定,因人或者要求而...

Java之Annotation(一)_wx三横兰的博客-程序员ITS203

文章目录Annotation格式使用位置如何定义[email protected]@[email protected]@Repeatable参数类型实践:自定义注解@LogAnnotationannotation就是一些元数据,提供一些数据,但是这些数据又不是程序里的一部分,它对实际的代码块不会有实际的影响。annotation有很多作用,其中下面三个是比较常见的:生成文档。比如我们想要统计每个方法的时间或者打log。生成代码、XML文件等等。生成代码主要是为了把公共的部分代码抽离出来,较

mybatis3.4.1源代码 - ognl__jan_的博客-程序员ITS203

${...} 是居于ognl表达式替换的package cn.java.demo.ibatis.internal.ognl;import lombok.extern.slf4j.Slf4j;import org.apache.ibatis.ognl.OgnlContext;import org.apache.ibatis.ognl.OgnlException;import org.apache.ibatis.ognl.OgnlRuntime;import org.apache.ibatis

随便推点

执行智慧:学习笔记_weixin_30537391的博客-程序员ITS203

DVD1:假如周围的人不太积极,你就不会太积极!财富来自于你认识的人。好利来蛋糕。一天结束了,你至少要认识一个人。1. 行动创造结果。 立刻把想法变成行动!干!只要干,就行!列出明确规划!失败的人不愿意往前冲!2. 没有行动的原因是心态问题(四大心态)。遇到问题马上说别人,自己没变化!原因说得越好,死得越彻底!“第一心态:遇到问题你就说是别人的问题,你立刻就原地踏...

quartus联合modelsim联合仿真_hai_x的博客-程序员ITS203

一、安装、破解这里安装的是quartus13.1和modelsim10.6d,具体破解网上有什么教程,这里不再赘述二、联合仿真 配置quartus 在Tools-&gt;License setup里面的EDA Tool Options进行modelsim的关联配置 新建工程、编写.v文件 进行start compilation进行全文件的编译 testbench的生成 修改生成testbensh 在上一步的生成\simulation\model

unity 使用 sqlite 数据库遇到的问题 unity android 使用sqlite_huaxiangsl的博客-程序员ITS203

在用unity做开发时,需要使用sqlite作为数据库,于是百度,方法基本一致1  Assets 中 建立文件夹 Plugins并且导入以下几个dllMono.Data.Sqlite.dllsqlite3.dllSystem.Data.dll2 代码实现代码可以参考  xuanyusong大大   http://www.xuanyusong.com/ar

angular router-outlet的一个好用的功能_weixin_43160044的博客-程序员ITS203

今天做项目遇到了一个难题,就是在页面中有一个子路由通过router-outlet去展示,但是有一个需求,就是需要根据它的跳转来获取不同的数据,一开始想着使用Input,Output方法尝试一下(没错,vue里面就可以在路由里使用事件传递,不过也是因为它没有设置对应的周期函数),但是很遗憾行不通,然后就又想了各种各样的方法,但要不就是没法实现,要不就是影响性能,直到我发现了router-outlet...

CUMT学习日记——数据库原理之面向考题复习_我叫方程的博客-程序员ITS203

CUMT学习日记——数据库原理之面向考题复习系列第一篇 计算机网络复习系列第二篇 计算机组成原理复习系列第三篇 微机原理与接口技术复习系列第四篇 计算机操作系统复习系列第五篇 数据库原理复习文章目录CUMT学渣日记——数据库原理之面向考题复习写在前面一、数据库原理复习回忆二、笔记写在前面突然回想起原来数据库没更,本着记录生活的目的更新了,本笔记质量较差,后面如果考矿大复习专业课再重新更新。一、数据库原理复习回忆当时学习状态一般,最后还好是看着往年的题和课后作业和MOOC最后勉强考

在Twitter上使用带有tensorflow的双向lstm在Twitter上命名实体识别ner_yuan xiong的博客-程序员ITS203

In this article, we shall discuss on how to use a recurrent neural network to solve Named Entity Recognition (NER) problem. NER is a common task in NLP systems. Given a text document, a NER system aim...

推荐文章

热门文章

相关标签