C#Window VS2015,Treeview动态绑定树节点绑定sqlC#Window VS2015,Treeview动态绑定树节点绑定sql


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


namespace WindowsFormsApplication12
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
           
        }

        public bool IsPostBack { get; private set; }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                DataSet ds = new DataSet();
                SqlDataAdapter da = new SqlDataAdapter("select * from dbo.Table3", "server=USER-M9T1I10TS8;database=db_2017;uid=sa;pwd=123;");
                da.Fill(ds);
                //DataTable dt =ds.Tables[0]; //从数据库里取出数据
                this.treeView1.Nodes.Clear();
                nodes(this.treeView1.Nodes, ds, 0);
                this.treeView1.CollapseAll();
            }

        }
        public string fid = "-1";
        private void nodes(TreeNodeCollection tnode, DataSet ds, int id)
        {
          
        //创建视图 ,应为只有一张表
        DataView dview = new DataView(ds.Tables[0]);
            //视图的好处,在于能方便筛选数据
            dview.RowFilter = "[fid]=" + id + "";
            //显示每个节点的标题,递归!
            foreach (DataRowView row in dview)
            {
                TreeNode node = new TreeNode();
                node.Text = row["name"].ToString();
                tnode.Add(node);
                nodes(node.Nodes, ds, int.Parse(row["id"].ToString()));

            }

        }

        private void nodes(object childNodes, DataSet ds, int v)
        {
            throw new NotImplementedException();
        }
    }

}



相关文章: