C# Linq 查询数据库(DataSet)生成 Tree

效果图如下

cs代码

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 TreeView
{
    public partial class FrmTreeView : Form
    {
        bool isShow = false;
        public FrmTreeView()
        {
            InitializeComponent();
            tvTree.Nodes.Add("湖南省");
        }

        private void tsmShowAdd_Click(object sender, EventArgs e)
        {
            if (!isShow)
            {
                DataSet ds = DatabaseHelper.GetDataSet();
                AddTreeNode(ds, "cf0dbde5-14d6-44be-9f71-4e5d302afc99", tvTree.TopNode);
                isShow = true;
            }
           
        }


        private void AddTreeNode(DataSet ds,string fatherKey,TreeNode Nodes)
        {
            var results = from result in ds.Tables[0].AsEnumerable() 
                          where result.Field<string>("SYS_FATHERKEY") == fatherKey 
                          select result;

            foreach (var item in results)
            {
                TreeNode node = new TreeNode();
                node.Text = item.Field<string>("SYS_NAME");
                
                if (Nodes == null)
                {
                    tvTree.Nodes.Add(Nodes);
                }
                else
                {
                    Nodes.Nodes.Add(node);
                }
                AddTreeNode(ds, item.Field<string>("SYS_KEY"),node);
            }
        }

    }
}
View Code

 数据库表的结构如下

posted on 2014-10-30 13:44  lovezj9012  阅读(461)  评论(0编辑  收藏  举报

导航