我正在尝试使用System.Data.SQLite将节点加载到c#winform treeview中。
目前我的数据库表如下所示:
ID Parent_ID Name
1 0 Apple
2 0 Pear
3 2 Grapes
4 3 Banana
我需要我的树视图看起来像这样:
Apple
Pear
-> Grapes
-> -> Banana
"葡萄"的Parent_ID为"2",使其成为"梨"的子节点,而"香蕉"的Parent_ID为"3",使其成为"葡萄"的子节点。
我对SQL不是很有经验,不确定如何从我的SQLite文件"数据库.db中获取数据,其中包含一个表"MyTable"。
任何帮助都非常感谢。
尝试以下操作:
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);
}
}
}
}
非常感谢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);
}
}
}
}