自定义控件---动态无限级生成 级联comboBox 和 treeView

时间:2021-01-30 12:40:33

开始 -〉新建 -〉新建项目 -〉“Windows窗体控件库”

名称栏 里 改为: myControl1

注: 若要添加城市国家区县等记录,请关联着 Area 表一同进行


上代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace myControls1
{
    public partial class UserControl1 : UserControl
    {
        private int LeftComboBox = 90;
        private int TopComboBox = 50;
        private int LeftRadioButton = 40;
        private int TopRadioButton = 48;
        private int Vertical = 45;
        public int ctWidth = 270;// tabControl 控件 属性
        public int ctHeight = 480;

        private TabControl tc = new TabControl();
        private TabPage tp层级 = new TabPage();
        private TabPage tp树型 = new TabPage();
        private TreeView tv = new TreeView();
        private Button button确定 = new Button();
        private RadioButton radioButtonTemp = new RadioButton();//临时的、不可见的

        private string connStr = "";
        private int _id_返回值 = 0;
        public bool flag { get; set; }
        public string tab表名1 { get; set; }
        public string tab表名2 { get; set; }

        public int id_返回值
        {
            get { return _id_返回值; }
        }

        private SqlConnection sqlconn;
        private DataSet ds = new DataSet();

        public UserControl1(string s)//s 系传进来的数据库连接字符串
        {
            connStr = s;
            InitializeComponent();
            sqlconn = new SqlConnection(connStr);
            flag = false;
        }

        private void UserControl1_Load(object sender, EventArgs e)
        {
            setMainControls(tab表名1, tab表名2);
        }

        /// <summary>
        /// tablename1 和 tablename2 系表名
        /// </summary>
        /// <param name="tablename1"></param>
        /// <param name="tablename2"></param>
        private void setMainControls(string tablename1, string tablename2)
        {
            tc.Location = new Point(40, 30);
            tc.Width = ctWidth;
            tc.Height = ctHeight;

            tp层级.Text = "层级";
            tp树型.Text = "树型";

            tv.Dock = DockStyle.Fill;

            tc.Controls.Add(tp层级);
            tp树型.Controls.Add(tv);
            tc.Controls.Add(tp树型);
            this.Controls.Add(tc);

            radioButtonTemp.Visible = false;
            tp层级.Controls.Add(radioButtonTemp);

            button确定.Location = new Point(130, 510);
            button确定.Text = "确 定";
            button确定.Enabled = false;
            this.Controls.Add(button确定);
            button确定.Show();
            button确定.Click += (s, e) => { ThisButtonClick(_id_返回值); };

            setSubControls(null, null, tablename1, tablename2, 1, 0);
        }

        //递归用
        private int xh = 1;
        private void setSubControls(DataTable _dt, BindingSource _bs, string tablename1, string tablename2, int layer, int v)
        {
            TopComboBox += v;
            TopRadioButton += v;

            if (_dt == null)
            {
                try
                {
                    DataTable dt1 = new DataTable();
                    DataTable dt2 = new DataTable();
                    using (SqlDataAdapter sda1 = new SqlDataAdapter("Select a.ID, a.Name,a.ParentID,a.Layer,b.name as qx from " + tablename1 + " as a," + tablename2 + " as b where a.Layer=" + layer + " and a.Layer=b.ID", sqlconn))
                    {
                        sda1.Fill(dt1);
                    }
                    using (SqlDataAdapter sda2 = new SqlDataAdapter("Select a.ID, a.Name,a.ParentID,a.Layer,b.name as qx from " + tablename1 + " as a," + tablename2 + " as b where a.Layer=" + (layer + 1) + " and a.Layer=b.ID", sqlconn))
                    {
                        sda2.Fill(dt2);
                    }
                    ds.Tables.Add(dt1);
                    ds.Tables.Add(dt2);
                    string relationsName = "r" + xh.ToString();
                    ds.Relations.Add(relationsName, dt1.Columns["id"], dt2.Columns["ParentID"]);
                    BindingSource bs = new BindingSource();
                    bs.DataSource = ds;
                    bs.DataMember = ds.Tables[0].ToString();

                    ComboBox cmb = new ComboBox();
                    cmb.Left = LeftComboBox;
                    cmb.Top = TopComboBox;
                    cmb.DropDownStyle = ComboBoxStyle.DropDownList;

                    RadioButton rb = new RadioButton();
                    rb.Left = LeftRadioButton;
                    rb.Top = TopRadioButton;
                    rb.Text = dt2.Rows[0]["qx"].ToString().Trim();
                    rb.Checked = false;

                    rb.MouseClick += (s, e) => { ThisRadioButtonClick(rb, cmb); };
                    cmb.SelectedIndexChanged += (s, e) => { ThisComboBoxClick(cmb); };

                    tp层级.Controls.Add(cmb);
                    tp层级.Controls.Add(rb);
                    cmb.Show();
                    rb.Show();

                    BindingSource bs1 = new BindingSource();
                    bs1.DataSource = bs;
                    bs1.DataMember = relationsName;
                    cmb.DataSource = bs1;
                    cmb.DisplayMember = "Name";
                    cmb.ValueMember = "id";

                    setSubControls(dt2, bs1, tablename1, tablename2, layer + 1, Vertical);


                    TreeNode[] root = new TreeNode[dt1.Rows.Count];
                    for (int i = 0; i < dt1.Rows.Count; i++)
                    {
                        root[i] = new TreeNode(dt1.Rows[i]["name"].ToString());
                        root[i].Tag = int.Parse(dt1.Rows[i]["id"].ToString());
                        tv.Nodes.Add(root[i]);
                        tv.AfterSelect += (s, e) => { ThisTreeViewNodeClick(s, e); };
                        DrawTreeView(root[i], int.Parse(dt1.Rows[i]["layer"].ToString()), int.Parse(dt1.Rows[i]["id"].ToString()), tablename1);
                    }
                }
                catch { }
            }
            else
            {
                try
                {
                    DataTable dt3 = new DataTable();
                    using (SqlDataAdapter sda3 = new SqlDataAdapter("Select a.ID,a.Name,a.ParentID,a.Layer,b.name as qx from " + tablename1 + " as a," + tablename2 + " as b where a.Layer=" + (layer + 1) + " and a.Layer=b.ID", sqlconn))
                    {
                        sda3.Fill(dt3);
                    }
                    ds.Tables.Add(dt3);
                    xh++;
                    string relationsName = "r" + xh.ToString();
                    ds.Relations.Add(relationsName, _dt.Columns["id"], dt3.Columns["ParentID"]);


                    ComboBox cmb = new ComboBox();
                    cmb.Left = LeftComboBox;
                    cmb.Top = TopComboBox;
                    cmb.DropDownStyle = ComboBoxStyle.DropDownList;

                    RadioButton rb = new RadioButton();
                    rb.Left = LeftRadioButton;
                    rb.Top = TopRadioButton;
                    rb.Text = dt3.Rows[0]["qx"].ToString().Trim();
                    rb.Checked = false;

                    rb.MouseClick += (s, e) => { ThisRadioButtonClick(rb, cmb); };
                    cmb.SelectedIndexChanged += (s, e) => { ThisComboBoxClick(cmb); };

                    tp层级.Controls.Add(cmb);
                    tp层级.Controls.Add(rb);
                    cmb.Show();
                    rb.Show();

                    BindingSource bs2 = new BindingSource();
                    bs2.DataSource = _bs;
                    bs2.DataMember = relationsName;
                    cmb.DataSource = bs2;
                    cmb.DisplayMember = "Name";
                    cmb.ValueMember = "id";

                    setSubControls(dt3, bs2, tablename1, tablename2, layer + 1, Vertical);
                }
                catch { }
            }

        }

        private void DrawTreeView(TreeNode treeNode, int layer, int id, string tablename)
        {
            DataTable dt = new DataTable();
            if (layer < 5)
            {
                using (SqlDataAdapter sda = new SqlDataAdapter("Select * from " + tablename + " as s where s.parentid=" + id, sqlconn))
                {
                    sda.Fill(dt);
                }

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    TreeNode SonNode = new TreeNode(dt.Rows[i]["name"].ToString());
                    SonNode.Tag = int.Parse(dt.Rows[i]["id"].ToString());
                    treeNode.Nodes.Add(SonNode);

                    DrawTreeView(SonNode, int.Parse(dt.Rows[i]["layer"].ToString()), int.Parse(dt.Rows[i]["id"].ToString()), tablename);
                }
            }
        }

        private void ThisButtonClick(int k)
        {
            flag = true;
            button确定.Enabled = false;
        }

        private void ThisComboBoxClick(ComboBox cmb)
        {
            radioButtonTemp.Checked = true;
        }

        private void ThisRadioButtonClick(RadioButton rb, ComboBox cmb)
        {
            rb.Checked = true;

            try
            {
                _id_返回值 = int.Parse(cmb.SelectedValue.ToString());
                button确定.Enabled = true;
            }
            catch
            {
                radioButtonTemp.Checked = true;
                button确定.Enabled = false;
            }
        }

        //private void treeViewTv_AfterSelect(object sender, TreeViewEventArgs e)
        private void ThisTreeViewNodeClick(object sender, TreeViewEventArgs e)
        {
            _id_返回值 = int.Parse(e.Node.Tag.ToString());
            button确定.Enabled = true;
        }
    }
}

点击:生成 -〉生成 myControl1 或者 重新生成 myControl1   => 生成my Control1.dll

使用:

WinForm 中 调用

1。引用:添加引用 myControl1.dll

2。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        private myControls1.UserControl1 f;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            f = new myControls1.UserControl1("Data Source=LocalHost;Integrated Security=SSPI;Initial Catalog=zl");
            f.tab表名1 = "country";
            f.tab表名2 = "area";
            f.Location = new Point(10, 10);
            this.Controls.Add(f);
            f.Show();
            
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (f.flag == true)
            {
                f.flag = false;
                MessageBox.Show(f.id_返回值.ToString());//获得了选定的城市的 id 值
            }
        }
    }
}

这里,timer1 是拖来的,Form1_Load(...   是双击form控件 产生的


运行结果:(本想录制个GIF的,没弄成,只得看图了)

自定义控件---动态无限级生成 级联comboBox 和 treeView自定义控件---动态无限级生成 级联comboBox 和 treeView


该上数据库了:见下图

自定义控件---动态无限级生成 级联comboBox 和 treeView自定义控件---动态无限级生成 级联comboBox 和 treeView