如何从SqlLite数据库加载TreeView节点

时间:2019-04-03 15:59:16

标签: c# .net sqlite treeview

我正在尝试使用System.Data.SQLite将节点加载到C#Winform树视图中。

当前我的数据库表如下:

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

我需要我的Treeview看起来像这样:

Apple
Pear
-> Grapes
-> -> Banana

'Grapes'的Parent_ID为'2',使其成为'Pear'的子节点,'Banana'的Parent_ID为'3',使其成为'Grapes'的子节点。

我对SQL不太熟悉,并且不确定如何从包含表“ MyTable”的SQLite文件“ Database.db”中获取数据。

非常感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

尝试以下操作:

  x.domain(this.data.map(function(d) { return d.ItemId; }));
  x1.domain(this.data.map(function(d) { return d.Category; }));
  x2.domain(this.data.map(function(d) { return d.Name; }));

答案 1 :(得分:0)

非常感谢Jdweng提供的解决方案。

我稍微修改了他们的代码,以使它不再依赖于手动创建数据表,而是从我的SQLite数据库文件中获取了数据。

Jdweng的代码还创建了一个“根”节点,这对于我的应用程序不是必需的,因此我将其更改为仅包括SQLite DB表中包含的节点。

我还需要更改“ MakeTree”方法以查找Int64,因为我收到一个错误,在查询ID和Parent_ID时“指定的转换无效”。

using System;
using System.Data;
using System.Data.SQLite;
using System.Linq;
using System.Windows.Forms;

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

        private void button1_Click(object sender, EventArgs e)
        {
            DataTable DT = new DataTable();

            SQLiteConnection sql_con = new SQLiteConnection("data source=\"mydatabase.db\"");
            sql_con.Open();
            SQLiteCommand sql_cmd = sql_con.CreateCommand();
            sql_cmd.CommandText = "SELECT * FROM mytable";
            SQLiteDataAdapter DA = new SQLiteDataAdapter(sql_cmd.CommandText, sql_con);

            DA.Fill(DT);

            sql_con.Close();


            int parentID = 0;
            MakeTree(parentID, treeView1.Nodes, DT);

            treeView1.ExpandAll();
        }

        public void MakeTree(Int64 parentID, TreeNodeCollection parentNode, DataTable DT)
        {
            foreach (DataRow row in DT.AsEnumerable().Where(x => x.Field<Int64>("Field2") == parentID))
            {
                string name = row.Field<string>("Field3");
                Int64 id = row.Field<Int64>("Field1");
                TreeNode node = new TreeNode(name);
                parentNode.Add(node);
                MakeTree(id, node.Nodes, DT);

            }
        }
    }
}