我的数据库表结构是这样的:
ID(主键),标题(Nvarchar),ParentID(这是当前表的ID)
并且第一个节点(root)的'ParentID'的值为-1 我将这些数据加载到内存中(例如在类列表中) 如何将带有循环或其他内容的项添加到TreeView?
答案 0 :(得分:2)
只需按ParentID订购数据,第一个结果将是root one(-1)。然后使用
if (ParentID == -1)
{
treeView1.Nodes.Add(ID, Title);
}
else
{
TreeNode tn = treeView1.Nodes.Find(ID, true)[0];
tn.Nodes.Add(ID, Title);
}
这就是你如何确保所有以前的节点都已经在树中,并通过唯一键(ID)找到它们。
答案 1 :(得分:0)
您可以循环数据并创建包含您要显示的数据的TreeNodes。您也可以根据需要为节点提供父节点(如果需要)。
然后,您可以将treenode添加到treeview的节点集合中。
答案 2 :(得分:0)
我写了这段代码:
private void Heading_Load(object sender, System.EventArgs e)
{
InsertNodes(null, 0);
}
private void InsertNodes(TreeNode n, int hdrID)
{
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=Acounting;Integrated Security=True;Pooling=False");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT hdrid,title FROM [Heading] WHERE ParentID=" + hdrID, con);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read()) {
TreeNode t = new TreeNode(rdr("title").ToString());
InsertNodes(t, Convert.ToInt16(rdr("hdrID").ToString()));
if (n == null) {
trvHeader.Nodes.Add(t);
} else {
n.Nodes.Add(t);
}
}
rdr.Close();
}
怎么回事?