Windows窗体VB.NET - 使用分层数据填充TreeView

时间:2010-02-05 10:06:28

标签: sql vb.net treeview hierarchical-data

阿罗哈, 我正在尝试使用来自SQL db的分层数据在Windows窗体应用程序上填充树视图。

数据库中的结构是:

id_def  id_parent description
1     NULL      Multidificiência
2     NULL      Síndrome
3     NULL      Outros
4     1       Surdez de Transmissão
5     2       Surdez Neurossensorial Ligeira
6     3       Surdez Neurossensorial Média

在id_parent中具有NULL值的记录是主要类别,而具有id_parent的记录是子类别。

任何人都可以帮助填充TreeView的代码吗? 我设法使用ASP.NET应用程序,如果它有帮助,这是代码:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
        PopulateRootLevel();
}

private void PopulateRootLevel()
{
    SqlConnection objConn = new SqlConnection("Data Source=1.1.1.1;Initial Catalog=DREER_EDUCANDOS2006;User ID=sre_web;Password=xxx");
    SqlCommand objCommand = new SqlCommand("select id_deficiencia,descricao,(select count(*) FROM NecessidadesEspeciais WHERE id_deficiencia_pai=sc.id_deficiencia) childnodecount FROM NecessidadesEspeciais sc where id_deficiencia_pai IS NULL", objConn);
    SqlDataAdapter da = new SqlDataAdapter(objCommand);
    DataTable dt = new DataTable();
    da.Fill(dt);
    PopulateNodes(dt, TreeView1.Nodes);
}

private void PopulateSubLevel(int parentid, TreeNode parentNode)
{
    SqlConnection objConn = new SqlConnection("Data Source=1.1.1.1;Initial Catalog=DREER_EDUCANDOS2006;User ID=sre_web;Password=xxx");
    SqlCommand objCommand = new SqlCommand("select id_deficiencia,descricao,(select count(*) FROM NecessidadesEspeciais WHERE id_deficiencia_pai=sc.id_deficiencia) childnodecount FROM NecessidadesEspeciais sc where id_deficiencia_pai=@id_deficiencia_pai", objConn);
    objCommand.Parameters.Add("@id_deficiencia_pai", SqlDbType.Int).Value = parentid;
    SqlDataAdapter da = new SqlDataAdapter(objCommand);
    DataTable dt = new DataTable();
    da.Fill(dt);
    PopulateNodes(dt, parentNode.ChildNodes);
}


protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e)
{
    PopulateSubLevel(Int32.Parse(e.Node.Value), e.Node);
}

private void PopulateNodes(DataTable dt, TreeNodeCollection nodes)
{
    foreach (DataRow dr in dt.Rows)
    {
        TreeNode tn = new TreeNode();
        tn.Text = dr["descricao"].ToString();
        tn.Value = dr["id_deficiencia"].ToString();
        nodes.Add(tn);

        //If node has child nodes, then enable on-demand populating
        tn.PopulateOnDemand = ((int)(dr["childnodecount"]) > 0);
    }
}

1 个答案:

答案 0 :(得分:2)

在表格中加入一些分层数据:

Id  Name                                ParentNodeId
1   Top-level node 1                    -1
2   A first-level child                  1
3   Another top-level node              -1
4   Another first-level child            1
5   First-level child in another branch  3
6   A second-level child                 2

我已经重新设计了来自another SO answer的示例代码,以使用上面的表动态填充树视图(假设该表位于SQL Server数据库中)。代码示例有点长......

using System.Windows.Forms;
using System.Threading;
using System.Collections.Generic;
using System.Data.SqlClient;
public class TreeViewSample : Form
{
    private TreeView _treeView;
    public TreeViewSample()
    {
        this._treeView = new System.Windows.Forms.TreeView();
        this._treeView.Location = new System.Drawing.Point(12, 12);
        this._treeView.Size = new System.Drawing.Size(200, 400);
        this._treeView.AfterExpand +=
            new TreeViewEventHandler(TreeView_AfterExpand);
        this.ClientSize = new System.Drawing.Size(224, 424);
        this.Controls.Add(this._treeView);
        this.Text = "TreeView Lazy Load Sample";
        PopulateChildren(null);
    }

    void TreeView_AfterExpand(object sender, TreeViewEventArgs e)
    {
        if (e.Node.Nodes.Count == 1 && e.Node.Nodes[0].Tag == "dummy")
        {
            PopulateChildren(e.Node);
        }
    }

    private void PopulateChildren(TreeNode parent)
    {
        // this node has not yet been populated, launch a thread
        // to get the data
        int? parentId = parent != null ? (parent.Tag as DataNode).Id : (int?)null;
        ThreadPool.QueueUserWorkItem(state =>
        {
            IEnumerable<DataNode> childItems = GetNodes(parentId);
            // load the data into the tree view (on the UI thread)
            _treeView.BeginInvoke((MethodInvoker)delegate
            {
                PopulateChildren(parent, childItems);
            });
        });
    }

    private void PopulateChildren(TreeNode parent, IEnumerable<DataNode> childItems)
    {
        TreeNodeCollection nodes = parent != null ? parent.Nodes : _treeView.Nodes;
        TreeNode child;
        TreeNode dummy;
        TreeNode originalDummyItem = parent != null ? parent.Nodes[0] : null;
        foreach (var item in childItems)
        {
            child = new TreeNode(item.Text);
            child.Tag = item;
            dummy = new TreeNode("Loading. Please wait...");
            dummy.Tag = "dummy";
            child.Nodes.Add(dummy);
            nodes.Add(child);
        }
        if (originalDummyItem != null)
        {
            originalDummyItem.Remove();
        }
    }

    private IEnumerable<DataNode> GetNodes(int? parentId)
    {
        List<DataNode> result = new List<DataNode>();
        using (SqlConnection conn = new SqlConnection(@"[your connection string]"))
        using (SqlCommand cmd = new SqlCommand("select * from Nodes where ParentNodeId = @parentNodeId", conn))
        {
            cmd.Parameters.Add(new SqlParameter("@parentNodeId", System.Data.SqlDbType.Int));
            cmd.Parameters["@parentNodeId"].Value = parentId != null ? parentId : -1;
            conn.Open();
            using (SqlDataReader reader = cmd.ExecuteReader())
            {
                int nodeIdCol = reader.GetOrdinal("NodeId");
                int nameCol = reader.GetOrdinal("Name");
                int parentIdCl = reader.GetOrdinal("ParentNodeId");
                while (reader.Read())
                {
                    result.Add(new DataNode
                       {
                           Id = reader.GetInt32(nodeIdCol),
                           Text = reader.GetString(nameCol),
                           ParentId = reader.IsDBNull(parentIdCl) ? (int?)null : reader.GetInt32(parentIdCl)
                       });
                }
            }
        }
        return result;
    }
}

public class DataNode
{
    public int Id { get; set; }
    public string Text { get; set; }
    public int? ParentId { get; set; }
}

使用Linq-to-SQL可能会使数据获取代码变得更漂亮,但我希望尽可能完整,因此我决定将其保留以保持代码量的减少。 。(这需要包含一些生成的Linq-to-SQL类)。