C# easyui ComboTree自定义控件 绑定数据与使用

来源:互联网 发布:php 分割成数组 编辑:程序博客网 时间:2024/05/16 01:19

关于easyUI ComboTree控件的使用,之前在网上查了些资料,没有完整的例子,自己研究改写了一个自定义控件,分享给大家。
这是运行效果图:
这里写图片描述
下面是自定义控件部分的代码:

控件前端:<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UCComboTree.ascx.cs" Inherits="DTcms.Web.admin.dxscg.UserControl.UCComboTree" %>    <div style="margin:10px 0;">        <a href="javascript:void(0)" class="easyui-linkbutton" onclick="getValue()">GetValue</a>        <a href="javascript:void(0)" class="easyui-linkbutton" onclick="setValue()">SetValue</a>        <a href="javascript:void(0)" class="easyui-linkbutton" onclick="disable()">Disable</a>        <a href="javascript:void(0)" class="easyui-linkbutton" onclick="enable()">Enable</a>    </div>    <input id="<%= this.UniqueID %>" class="easyui-combotree" style="width:200px;">    <script type="text/javascript">        $(function () {            $('#<%= this.UniqueID %>').combotree({                multiple: false,//是否有复选框                cascadeCheck: false,//选择上级节点是否全选下级菜单                valueField: 'id',                textField: 'text',                //data: JSON.parse($('#<%= this.hfData.ClientID  %>').val()),                //这里使用的是测试数据                data: [{                    "id": 11,                    "text": "Photos",                    "state": "closed",                    "children": [{                        "id": 111,                        "text": "Friend"                    }, {                        "id": 112,                        "text": "Wife"                    }, {                        "id": 113,                        "text": "Company"                    }]                }, {                    "id": 12,                    "text": "Program Files",                    "children": [{                        "id": 121,                        "text": "Intel"                    }, {                        "id": 122,                        "text": "Java",                        "attributes": {                            "p1": "Custom Attribute1",                            "p2": "Custom Attribute2"                        }                    }, {                        "id": 123,                        "text": "Microsoft Office"                    }, {                        "id": 124,                        "text": "Games",                        "checked": true                    }]                }, {                    "id": 13,                    "text": "index.html"                }, {                    "id": 14,                    "text": "about.html"                }, {                    "id": 15,                    "text": "welcome.html"                }],                onLoadSuccess: function(node, data) {                    $('#<%= this.UniqueID %>').combotree('setValue', $('#<%= this.hfSeletedId.ClientID  %>').val());                },                onClick: function (node) {                    var val = $('#<%= this.UniqueID %>').combotree('getValue');                    $('#<%= this.hfSeletedId.ClientID  %>').val(val)                }            });        })        function getValue() {            var val = $('#<%= this.UniqueID %>').combotree('getValue');            alert(val);        }        function setValue() {            $('#<%= this.UniqueID %>').combotree('setValue', '3222');        }        function disable() {            $('#<%= this.UniqueID %>').combotree('disable');        }        function enable() {            $('#<%= this.UniqueID %>').combotree('enable');        }    </script><asp:HiddenField runat="server" ID="hfSeletedId"/><asp:HiddenField runat="server" ID="hdInfoSelectAddName"/><asp:HiddenField runat="server" ID="hfData"/>

自定义控件后台代码:

using DXSCG.DataAccess.Entity;using DXSCG.DataAccess.Query;using SO.DataAccess;using System;using System.Collections.Generic;using System.Data;using XJ.Web.admin.XJ;using static DTcms.Web.admin.dxscg.UserControl.GetTreeData;namespace DTcms.Web.admin.dxscg.UserControl{    public partial class UCComboTree : UserControlBase    {        protected void Page_Load(object sender, EventArgs e)        {        }        //获取date数据和默认value        public void SetValue(string strJson, string code)        {            this.hfData.Value = strJson;            this.hfSeletedId.Value = code;        }        //输出选中的value值        public void GetValue(out int id)        {            id = 0;            string str_id = (string)this.Request.Form[this.hfSeletedId.ClientID.Replace("_","$")];            this.hfSeletedId.Value = str_id;            if (string.IsNullOrEmpty(str_id))            {                return;            }            id = Convert.ToInt32( str_id);        }        //获得组织架构Tree            public string GetComList(ISession iSession, int catalogID)        {            EDict.Schema s = new EDict.Schema();            DataTable dt = QDict.GetTable(iSession, s.DictCatalogID == catalogID, null);            return GetJson(dt);        }        //获取json        public string GetJson(DataTable dt)        {            string json = "[";            IList<Tree> t = GetTreeData.returnParentTree(dt);            foreach (Tree model in t)            {                if (model != t[t.Count - 1])                {                    json += GetJsonByModel(model, dt) + ",";                }                else                {                    json += GetJsonByModel(model, dt);                }            }            json += "]";            json = json.Replace("'", "\"");            return json;        }        public static string GetJsonByModel(Tree t, DataTable dt)        {            string json = "";            bool flag = GetTreeData.isHaveChild(t.ID, dt);            json = "{"                      + "'id':'" + t.Code + "',"                      + "'text':'" + t.Name + "',"                      + "'iconCls':'ok',"                      + "'children':";            if (!flag)            {                json += "null}";            }            else            {                json += "[";                IList<Tree> list = GetTreeData.getChild(t.ID, dt);                foreach (Tree tree in list)                {                    if (tree != list[list.Count - 1])                    {                        json += GetJsonByModel(tree, dt) + ",";                    }                    else                    {                        json += GetJsonByModel(tree, dt);                    }                }                json += "],'state':'closed'}";            }            return json;        }    }    //组织机构tree    public class GetTreeData    {        public static IList<Tree> returnParentTree(DataTable dtset)        {            DataTable dt = GetData(dtset, 0);            IList<Tree> t = new List<Tree>();            foreach (DataRow dr in dt.Rows)            {                Tree tParent = new Tree();                tParent.ID = Int32.Parse(dr["DictID"].ToString());                tParent.Code = Int32.Parse(dr["Code"].ToString());                tParent.Name = dr["Name"].ToString();                t.Add(tParent);            }            return t;        }        public static bool isHaveChild(int id, DataTable dtset)        {            bool flag = false;            DataTable dt = GetData(dtset, id);            if (dt.Rows.Count > 0)            {                flag = true;            }            return flag;        }        public static IList<Tree> getChild(int id, DataTable dtset)        {            IList<Tree> t = new List<Tree>();            DataTable dt = GetData(dtset, id);            foreach (DataRow dr in dt.Rows)            {                Tree tParent = new Tree();                tParent.ID = Int32.Parse(dr["DictID"].ToString());                tParent.Code = Int32.Parse(dr["Code"].ToString());                tParent.Name = dr["Name"].ToString();                t.Add(tParent);            }            return t;        }        //根据父节点得到子集        private static System.Data.DataTable GetData(DataTable dt, int pid)        {            DataTable dtResult = dt.Clone();            foreach (DataRow item in dt.Rows)            {                if(item["ParentID"].ToString() == "")                {                    item["ParentID"] = 0;                }                if (Convert.ToInt32(item["ParentID"]) == pid)                {                    DataRow dr = dtResult.NewRow();                    dr["Code"] = item["Code"];                    dr["DictID"] = item["DictID"];                    dr["Name"] = item["Name"];                    dr["ParentID"] = item["ParentID"];                    dtResult.Rows.Add(dr);                }            }            return dtResult;        }        public class Tree        {            public int ID { get; set; }            public int Code { get; set; }            public string Name { get; set; }        }    }}

下面是测试页面代码:

测试页面前端:<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="DTcms.Web.admin.dxscg.Home.WebForm1" %><%@ Register Src="~/admin/dxscg/UserControl/UCComboTree.ascx" TagPrefix="uc1" TagName="UCComboTree" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>    <title></title>    <link href="../../../scripts/easyui/themes/default/easyui.css" rel="stylesheet" />    <link href="../../../scripts/easyui/themes/icon.css" rel="stylesheet" />    <script src="../../../scripts/easyui/jquery-1.8.0.min.js"></script>    <script src="../../../scripts/easyui/jquery.easyui.min.js"></script></head><body>    <form id="form1" runat="server">    <div>        <%--<uc1:UCComboTree runat="server" ID="UCComboTree1" />--%>        <uc1:UCComboTree runat="server" id="UCComboTree" />    </div>        <asp:Button ID="Button1" runat="server" Text="Button"  OnClick="btnSubmit_Click" />    </form></body></html>
测试页面后台代码:using System;namespace DTcms.Web.admin.dxscg.Home{    public partial class WebForm1 : DXSCG.Web.admin.DXSCG.PageBase    {        protected void Page_Load(object sender, EventArgs e)        {            bindDate();        }        private void bindDate()        {            this.OpenSession((iSession) =>            {                string s = UCComboTree.GetComList(iSession , 3056);                UCComboTree.SetValue(s, "1001");                //string s1 = UCComboTree1.GetComList(iSession, 3053);                //UCComboTree1.SetValue(s1, "3001");            }            , "databind", "绑定数据", false, "", "back");        }        protected void btnSubmit_Click(object sender, EventArgs e)        {            int id;            this.UCComboTree.GetValue(out id);        }    }}

因为时间关系,只是简单的写了一下,还有很多地方待改善。