treeView自动更新数据

今天分享一份新作的程序,它的功能是通过连接数据库将数据更新到treeView控件中。

这是页面设计中的界面。记得要加sqlConnection。

接下来在Form1_Load中添加下列代码


        private void Form1_Load(object sender, EventArgs e)
        {
            treeView1.LabelEdit = true;    //打开treeView的修改功能
            //连接数据库
            string vSqlSampleName = ".";
            string vSqlDBName = "SunRiseERP";
            string vSqlUserCode = "sa";
            string vSqlPassword = "63351477";
            string vConnectionString =
                                 "Pooling=true;Min Pool Size=10;Max Pool Size=20;Data Source=" + vSqlSampleName
                                 + ";Initial Catalog=" + vSqlDBName + ";Persist Security Info=false;"
                                 + "User ID=" + vSqlUserCode + ";Password=" + vSqlPassword
                                 + ";MultipleActiveResultSets=true";
            this.sqlConnection1.ConnectionString = vConnectionString;
            this.sqlConnection1.Open();
            Getselect_eCBMExpense();  //将sql数据更新到treeView中
        }

并建一个Getselect_eCBMExpense供其调用

public void Getselect_eCBMExpense()
        {
            treeView1.Nodes.Clear();
            DataTable dt= new DataTable();
            string sql = "select * from tbasDepartmentTree";
            using (SqlCommand cmd = new SqlCommand(sql, this.sqlConnection1))
            {
                SqlDataReader dr = cmd.ExecuteReader();
                dt.Load(dr);
                dr.Close();
            }
            foreach (DataRow row in dt.Rows)
            {
                string nodeid = Convert.ToString(row["NodeID"]);  //在数据库中提取NodeID的数据
                string id = Convert.ToString(row["NodeParentID"]);  //在数据库中提取NodeParentID的数据
                if (id == "0")  //NodeParentID的一级分类值为“0”
                {
                    TreeNode node = new TreeNode();
                    node.Text = Convert.ToString(row["NodeCode"]);
                    this.treeView1.Nodes.Add(node);        //添加一级分类
                    BindData(nodeid, dt, node);             //添加子分类
                }
            }
        }
        public void BindData(string parId, DataTable dt, TreeNode parNode)
        {
            foreach (DataRow row in dt.Rows)
            {
                string nodeid = Convert.ToString(row["NodeID"]); //在数据库中提取NodeID的数据
                string id = Convert.ToString(row["NodeParentID"]);  //在数据库中提取NodeParentID的数据
                if (id == parId)
                {
                    TreeNode node = new TreeNode();
                    node.Text = Convert.ToString(row["NodeCode"]);
                    parNode.Nodes.Add(node);
                    BindData(nodeid, dt, node);
                }
            }
        }

运行之后即可实现数据自动更新


你可能感兴趣的:(C#)