Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

c# - How to load TreeView nodes from SqlLite database

I am trying to load nodes into a c# winform treeview using System.Data.SQLite.

Currently my database table looks like this:

ID  Parent_ID  Name 
1   0          Apple
2   0          Pear 
3   2          Grapes 
4   3          Banana

I need my treeview to look like this:

Apple
Pear
-> Grapes
-> -> Banana

'Grapes' has a Parent_ID of '2', making it a child node of 'Pear', and 'Banana' has a Parent_ID of '3', making it a child node of 'Grapes'.

I'm not very experienced with SQL and am not sure how to go about getting the data out of my SQLite file 'Database.db', containing a table 'MyTable'.

Any help is much appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try following :

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 WindowsFormsApplication41
{
    public partial class Form1 : Form
    {
        DataTable dt = null;
        public Form1()
        {
            InitializeComponent();

            dt = new DataTable();
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("Parent_ID", typeof(int));
            dt.Columns.Add("Name", typeof(string));

            dt.Rows.Add(new object[] {1, 0, "Apple"});
            dt.Rows.Add(new object[] {2, 0, "Pear"});
            dt.Rows.Add(new object[] {3, 2, "Grapes"});
            dt.Rows.Add(new object[] {4, 3, "Banana"});

            TreeNode node = new TreeNode("Root");
            treeView1.Nodes.Add(node);
            int parentID = 0;
            MakeTree(parentID, node);

            treeView1.ExpandAll();
        }

        public void MakeTree(int parentID, TreeNode parentNode)
        {
            foreach(DataRow row in dt.AsEnumerable().Where(x => x.Field<int>("Parent_ID") == parentID))
            {
                string name = row.Field<string>("Name");
                int id = row.Field<int>("ID");
                TreeNode node = new TreeNode(name);
                parentNode.Nodes.Add(node);
                MakeTree(id, node);

            }
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...