Popolare TreeView da DataBase

Popolare TreeView da DataBase

Probabilmente sarà qualcosa del genere. Fornisci qualche dettaglio in più su cosa esattamente vuoi fare se hai bisogno di più.

//In Page load
foreach (DataRow row in topics.Rows)
{
    TreeNode node = new TreeNode(dr["name"], dr["topicId"])
    node.PopulateOnDemand = true;

     TreeView1.Nodes.Add(node);
 }
 ///
 protected void PopulateNode(Object sender, TreeNodeEventArgs e)
 {
     string topicId = e.Node.Value;
     //select from topic where parentId = topicId.
     foreach (DataRow row in topics.Rows)
     {
         TreeNode node = new TreeNode(dr["name"], dr["topicId"])
         node.PopulateOnDemand = true;

         e.Node.ChildNodes.Add(node);
     }

 }

Non proprio.

Gli alberi di solito vengono gestiti al meglio non caricando tutto ciò che puoi in una volta. Quindi è necessario ottenere il nodo principale (o argomento) che non ha parentID. Quindi aggiungili al nodo radice degli alberi e quindi per ogni nodo che aggiungi devi ottenere i suoi figli.

foreach (DataRow row in topicsWithOutParents.Rows)
{
   TreeNode node = New TreeNode(... whatever);
   DataSet childNodes = GetRowsWhereParentIDEquals(row["topicId"]);
   foreach (DataRow child in childNodes.Rows)
   { 
       Treenode childNode = new TreeNode(..Whatever);
       node.Nodes.add(childNode);
   }
   Tree.Nodes.Add(node);
}

questo codice funziona perfettamente per me, dai un'occhiata penso che ti aiuterà :)

;

protected void Page_Load(object sender, EventArgs e)
{
    DataSet ds = RunQuery("Select topicid,name from Topics where Parent_ID IS NULL");
       for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
       { 
           TreeNode root = new TreeNode(ds.Tables[0].Rows[i][1].ToString(),ds.Tables[0].Rows[i][0].ToString());
           root.SelectAction = TreeNodeSelectAction.Expand;
           CreateNode(root);
           TreeView1.Nodes.Add(root);
       }



}
void CreateNode(TreeNode node)
{
    DataSet ds = RunQuery("Select topicid, name from Category where Parent_ID =" + node.Value);
    if (ds.Tables[0].Rows.Count == 0)
    {
        return;
    }
    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
    {
        TreeNode tnode = new TreeNode(ds.Tables[0].Rows[i][1].ToString(), ds.Tables[0].Rows[i][0].ToString());
        tnode.SelectAction = TreeNodeSelectAction.Expand;
        node.ChildNodes.Add(tnode);
        CreateNode(tnode);
    }

}
DataSet RunQuery(String Query)
{
    DataSet ds = new DataSet();
    String connStr = "???";//write your connection string here;
    using (SqlConnection conn = new SqlConnection(connStr))
    {
        SqlCommand objCommand = new SqlCommand(Query, conn);
        SqlDataAdapter da = new SqlDataAdapter(objCommand);
        da.Fill(ds);
        da.Dispose();
    }
    return ds;
}