在Winform中,可以通過(guò)遞歸方式加載數(shù)據(jù)庫(kù)數(shù)據(jù)到TreeView中。下面是一個(gè)簡(jiǎn)單的示例代碼:
首先,創(chuàng)建一個(gè)TreeView控件和一個(gè)Button控件:
TreeView treeView1 = new TreeView();
Button button1 = new Button();
button1.Text = "Load Data";
button1.Click += Button1_Click;
然后,在Button的Click事件中編寫遞歸加載數(shù)據(jù)庫(kù)數(shù)據(jù)的代碼:
private void Button1_Click(object sender, EventArgs e)
{
treeView1.Nodes.Clear(); // 清空TreeView節(jié)點(diǎn)
// 連接數(shù)據(jù)庫(kù)并查詢數(shù)據(jù)
using (SqlConnection conn = new SqlConnection("YourConnectionString"))
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM YourTable", conn);
SqlDataReader reader = cmd.ExecuteReader();
// 遞歸加載數(shù)據(jù)到TreeView中
while (reader.Read())
{
LoadDataToTreeView(treeView1.Nodes, reader);
}
}
}
private void LoadDataToTreeView(TreeNodeCollection nodes, SqlDataReader reader)
{
TreeNode node = new TreeNode(reader["ColumnName"].ToString());
nodes.Add(node);
// 遞歸加載子節(jié)點(diǎn)數(shù)據(jù)
using (SqlConnection conn = new SqlConnection("YourConnectionString"))
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM YourTable WHERE ParentID = @ID", conn);
cmd.Parameters.AddWithValue("@ID", reader["ID"]);
SqlDataReader subReader = cmd.ExecuteReader();
while (subReader.Read())
{
LoadDataToTreeView(node.Nodes, subReader);
}
}
}
在LoadDataToTreeView方法中,首先創(chuàng)建一個(gè)TreeNode對(duì)象并添加到指定的節(jié)點(diǎn)集合中。然后根據(jù)父節(jié)點(diǎn)的ID查詢子節(jié)點(diǎn)數(shù)據(jù),并遞歸調(diào)用LoadDataToTreeView方法加載子節(jié)點(diǎn)數(shù)據(jù)。
最后,在Button的Click事件中調(diào)用LoadDataToTreeView方法加載根節(jié)點(diǎn)數(shù)據(jù),實(shí)現(xiàn)數(shù)據(jù)庫(kù)數(shù)據(jù)的遞歸加載到TreeView中。