在Winform中,可以通過遞歸方式加載數據庫數據到TreeView中。下面是一個簡單的示例代碼:
首先,創建一個TreeView控件和一個Button控件:
TreeView treeView1 = new TreeView();
Button button1 = new Button();
button1.Text = "Load Data";
button1.Click += Button1_Click;
然后,在Button的Click事件中編寫遞歸加載數據庫數據的代碼:
private void Button1_Click(object sender, EventArgs e)
{
treeView1.Nodes.Clear(); // 清空TreeView節點
// 連接數據庫并查詢數據
using (SqlConnection conn = new SqlConnection("YourConnectionString"))
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM YourTable", conn);
SqlDataReader reader = cmd.ExecuteReader();
// 遞歸加載數據到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);
// 遞歸加載子節點數據
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方法中,首先創建一個TreeNode對象并添加到指定的節點集合中。然后根據父節點的ID查詢子節點數據,并遞歸調用LoadDataToTreeView方法加載子節點數據。
最后,在Button的Click事件中調用LoadDataToTreeView方法加載根節點數據,實現數據庫數據的遞歸加載到TreeView中。