自定义控件之三级联动

1类代码

 //要引用到的命名空间
using System.Web.UI;
using System.ComponentModel;
using System.Data;
using System.Web.UI.WebControls;

namespace ClassLibrary
{
    [ToolboxData("<{0}:ThreeLinkableList runat=server></{0}:ThreeLinkableList>")]
    public class ThreeLinkableList : WebControl
    {
        #region Properties

        /// <summary>
        /// 需要有2至三个字段,第一个字段是在下拉列表内唯一选项标识;第二个字段是选项文本,第三个字段是上级选项的标识
        /// </summary>
        [Browsable(true)]
        [Category("Data")]
        [Description("用于分别绑定各级下拉列表的DataTable数组")]
        public DataTable[] DataSource
        {
            get
            {
                return _dataSource;
            }

            set
            {
                _dataSource = value;
            }
        }

        [Browsable(true)]
        [Category("Appearance")]
        [Description("指定排列多个下拉列表的方向")]
        public RepeatDirection Direction
        {
            get
            {
                return ViewState["Direction"] == null ? RepeatDirection.Horizontal : (RepeatDirection)ViewState["Direction"];
            }

            set
            {
                ViewState["Direction"] = value;
            }
        }

        protected override HtmlTextWriterTag TagKey
        {
            get
            {
                return HtmlTextWriterTag.Table;
            }
        }

        [Browsable(false)]
        public string[] PostBackValues
        {
            get
            {
                string[] rval = new string[_dropDownLists.Count];
                for (int i = 0; i < _dropDownLists.Count; i++)
                {
                    rval[i] = _dropDownLists[i].SelectedValue;
                }
                return rval;
            }
        }

        [Browsable(false)]
        public int[] SelectedIndexs
        {
            get
            {
                int[] rval = new int[_dropDownLists.Count];
                for (int i = 0; i < _dropDownLists.Count; i++)
                {
                    rval[i] = _dropDownLists[i].SelectedIndex;
                }
                return rval;
            }
        }

        [Browsable(true)]
        [Category("Appearance")]
        [Description("指定排列多个下拉列表的方向")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        [TypeConverter(typeof(ExpandableObjectConverter))]
        [NotifyParentProperty(true)]
        public Style DropDownListStyle
        {
            get
            {
                return _dropDownListStyle;
            }
        }

        #endregion

        #region Index

        public DropDownList this[int index]
        {
            get
            {
                return _dropDownLists[index];
            }
        }

        public DropDownList this[string name]
        {
            get
            {
                return this.FindControl(name) as DropDownList;
            }
        }

        #endregion

        #region Methods

        public override void DataBind()
        {
            if (Direction == RepeatDirection.Horizontal)
            {
                Literal l = new Literal();
                l.Text = "<tr>";
                this.Controls.Add(l);
            }

            if (_dataSource != null && _dataSource.Length != 0)
            {
                Page.ClientScript.RegisterClientScriptBlock(typeof(ThreeLinkableList), "refreshNext", refreshNext, true);
                Page.ClientScript.RegisterClientScriptBlock(typeof(ThreeLinkableList), "refreshNextForPostBack", refreshNextForPostBack, true);
                Page.ClientScript.RegisterClientScriptBlock(typeof(ThreeLinkableList), string.Concat("initCDDL", this.UniqueID), initCDDL, true);

                for (int i = 0; i < _dataSource.Length; i++)
                {
                    DataTable dt = _dataSource[i];
                    if (dt.Rows.Count == 0)
                    {
                        if (i == 0)
                        {   //如果第一个表就是空的
                            Literal l = new Literal();
                            l.Text = "<td></td>";
                            this.Controls.Add(l);
                        }
                        break;
                    }

                    Literal left = new Literal();
                    this.Controls.Add(left);
                    if (Direction == RepeatDirection.Horizontal)
                    {
                        left.Text = "<td>";
                    }
                    else
                    {
                        left.Text = "<tr><td>";
                    }

                    DropDownList ddl = new DropDownList();
                    ddl.ID = string.Concat("ddl_", i.ToString());
                    this.Controls.Add(ddl);
                    this._dropDownLists.Add(ddl);
                    ddl.ControlStyle.CopyFrom(_dropDownListStyle);

                    for (int j = 0; j < dt.Rows.Count; j++)
                    {
                        ListItem li = new ListItem();
                        li.Value = dt.Rows[j][0].ToString();
                        li.Text = dt.Rows[j][1].ToString();
                        if (i != 0)
                        {
                            li.Attributes["ParentPtr"] = dt.Rows[j][2].ToString();
                        }

                        ddl.Items.Add(li);
                    }

                    Literal right = new Literal();
                    this.Controls.Add(right);
                    if (Direction == RepeatDirection.Horizontal)
                    {
                        right.Text = "</td>";
                    }
                    else
                    {
                        right.Text = "</td></tr>";
                    }

                    Page.ClientScript.RegisterStartupScript(typeof(ThreeLinkableList), i.ToString(), string.Concat(initCDDL_ref + "(document.getElementById('", ddl.ClientID, "'));"), true);
                    ddl.Attributes["onchange"] = refreshNext_ref + "(document.getElementById('" + ddl.ClientID + "'))";
                }
            }

            if (Direction == RepeatDirection.Horizontal)
            {
                Literal l = new Literal();
                l.Text = "</tr>";
                this.Controls.Add(l);
            }

            base.DataBind();
        }

        protected override void OnPreRender(EventArgs e)
        {
            if (this.Controls.Count == 0)
            {
                Literal l = new Literal();
                l.Text = "<td></td>";
                this.Controls.Add(l);
            }
            else
            {
                ViewState["DataSource"] = _dataSource;
                if (!Page.IsPostBack)
                {
                    Page.ClientScript.RegisterStartupScript(typeof(ThreeLinkableList), this.ClientID, refreshNext_ref + "(document.getElementById('" + _dropDownLists[0].ClientID + "'));", true);
                }
                else
                {
                    Page.ClientScript.RegisterStartupScript(typeof(ThreeLinkableList), this.ClientID, refreshNextForPostBack_ref + "(document.getElementById('" + _dropDownLists[0].ClientID + "'));", true);
                }
            }

            base.OnPreRender(e);
        }

        protected override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);

            //回传状态还原
            _dataSource = ViewState["DataSource"] as DataTable[];
            DataBind();
        }

        #endregion

        #region Fields

        private DataTable[] _dataSource;
        private List<DropDownList> _dropDownLists = new List<DropDownList>();
        private Style _dropDownListStyle = new Style();
        private static string initCDDL;
        private static string initCDDL_ref;
        private static string refreshNext;
        private static string refreshNext_ref;
        private static string refreshNextForPostBack_ref;
        private static string refreshNextForPostBack;

        #endregion

        static ThreeLinkableList()
        {
            refreshNext_ref = string.Concat("zhyFunc_", typeof(ThreeLinkableList).FullName.Replace('.', 'I'), "_refreshNext");
            initCDDL_ref = string.Concat("zhyFunc_", typeof(ThreeLinkableList).FullName.Replace('.', 'I'), "_initCDDL");
            refreshNextForPostBack_ref = string.Concat("zhyFunc_", typeof(ThreeLinkableList).FullName.Replace('.', 'I'), "_refreshNextForPostBack");

            refreshNext = string.Concat("function ", refreshNext_ref, @"(list)
            {
                var nextList;
                try
                {
                    var index = list.id.lastIndexOf('_');
                    var front = list.id.substring(0,index+1);
                    var count = list.id.substring(index+1);
                    var count2 = parseInt(count)+1;
                    nextList = document.getElementById(front + count2);
                    if(!nextList)
                    {
                        return;
                    }
                }
                catch(e)
                {   //没有下一级
                    return;
                }

                while(nextList.options.length!=0)
                {   //移除下级下拉列表的所有item
                    nextList.options.remove(0);
                }

                for(var i=0;i<nextList.bakOptions.length;i++)
                {
                    if(nextList.bakOptions[i].ParentPtr == list.options[list.selectedIndex].value)
                    {
                        nextList.options.add(nextList.bakOptions[i]);
                    }
                }
                nextList.selectedIndex=0;" + refreshNext_ref + @"(nextList);
            }
");
            refreshNextForPostBack = string.Concat("function ", refreshNextForPostBack_ref, @"(list)
            {
                var nextList;
                try
                {
                    var index = list.id.lastIndexOf('_');
                    var front = list.id.substring(0,index+1);
                    var count = list.id.substring(index+1);
                    var count2 = parseInt(count)+1;
                    nextList = document.getElementById(front + count2);
                    if(!nextList)
                    {
                        return;
                    }
                }
                catch(e)
                {   //没有下一级
                    return;
                }

                for(var i=0;i<nextList.options.length;)
                {
                    if(nextList.options[i].ParentPtr != list.options[list.selectedIndex].value)
                    {
                        nextList.options.remove(i);
                    }
                    else
                    {
                        i++;
                    }
                }" + refreshNextForPostBack_ref + @"(nextList);
            }
");

            initCDDL = string.Concat("function ", initCDDL_ref, @"(list)
            {
                list.bakOptions = new Array();
                for(var i=0; i<list.options.length;i++)
                {   //保存所有item
                    list.bakOptions.push(list.options.item(i));
                }
            }
");
        }
    }
}

 

2数据库

create database ThreeLinkable
use ThreeLinkable
--省
create table province
(
    ProvinceID int primary key identity(1,1),
    ProvinceName nvarchar(50) not null,
)

--市
create table city
(
    CityID int primary key identity(1,1),
    CityName nvarchar(50) not null,
    ProvinceID int references province(ProvinceID)
)

--县
create table country
(
    CountryID    int primary key identity(1,1),
    CountryName nvarchar(50) not null,
    CityID int references city(CityID)
)
go

insert into province values('苏州')
insert into province values('安徽')

insert into city values('吴中',1)
insert into city values('相成',1)
insert into city values('安庆',2)
insert into city values('黄山',2)

insert into country values('小吴中',1)
insert into country values('小相成',2)
insert into country values('枞阳',3)
insert into country values('小黄山',4)

 

3页面Aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ThreeLinkControl.aspx.cs" Inherits="Web.DefinControlPractise.ThreeLinkControl" %>

<%@ Register Assembly="ClassLibrary" Namespace="ClassLibrary" TagPrefix="cc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <cc1:ThreeLinkableList ID="myDropdown"  runat="server"  DropDownListStyle-BackColor="AliceBlue" DropDownListStyle-Width="160px" Font-Bold="False"  />
</asp:Content>

 

4页面Aspx.cs

protected void Page_Load(object sender, EventArgs e)
        {
            string constr = System.Configuration.ConfigurationManager.AppSettings["constr"];
            DataTable[] dts = new DataTable[] { new DataTable(), new DataTable(),new DataTable() };
            SqlDataAdapter da = new SqlDataAdapter("select * from province", constr);
            da.Fill(dts[0]);
            da.SelectCommand.CommandText = "select * from city";
            da.Fill(dts[1]);
            da.SelectCommand.CommandText = "select * from country ";
            da.Fill(dts[2]);
            myDropdown.DataSource = dts;
            myDropdown.DataBind();

          

        }

 

推荐博客:RyanDoc数据字典 For SqlServer版            RyanCoder代码生成器 For SqlServer版

你可能感兴趣的:(自定义控件)