Member_4438002
asked on
Adding TreeView nodes at runtime, but Node count stays at 1
Hi,
I have a treeview control that populates from a database. I hardcoded a root node, and using PopulateOnDemand I believe this attempts to populate the TreeView when opening the page
The treeview populates OK, without a problem. However the issue is coming where I want to add another node to one of the nodes added at run time. It is only counting 1 node (so therefore, I cannot iterate through all the nodes to find the one I'm adding to, as the program believes there is only one node!)
I have a treeview control that populates from a database. I hardcoded a root node, and using PopulateOnDemand I believe this attempts to populate the TreeView when opening the page
The treeview populates OK, without a problem. However the issue is coming where I want to add another node to one of the nodes added at run time. It is only counting 1 node (so therefore, I cannot iterate through all the nodes to find the one I'm adding to, as the program believes there is only one node!)
<!--aspx file-->
<asp:TreeView ID="tvTariff" runat="server" OnSelectedNodeChanged="tvTariff_SelectedNodeChanged" OnTreeNodePopulate="tvTariff_TreeNodePopulate" ShowLines="True">
<Nodes>
<asp:TreeNode PopulateOnDemand="True" Text="Tariff List" Value="Tariff List"></asp:TreeNode>
</Nodes>
</asp:TreeView>
//C#
protected void tvTariff_TreeNodePopulate(object sender, TreeNodeEventArgs e)
{
if (e.Node.ChildNodes.Count == 0)
{
switch (e.Node.Depth)
{
case 0:
//Tariff - root
PopulateParent(e.Node);
break;
case 1:
//Add Code Group - tariff clicked on
PopulateCodeGroup(e.Node);
break;
}
}
}
void PopulateParent(TreeNode node)
{
//TreeViewSrc is a class file that returns the data from the database
TreeViewSrc trSrc = new TreeViewSrc();
DataTable dtRoot = new DataTable("Tariff");
dtRoot = trSrc.RootNodes();
foreach (DataRow row in dtRoot.Rows)
{
TreeNode NewNode = new TreeNode(row["ta_name"].ToString(), row["ta_id"].ToString());
NewNode.PopulateOnDemand = true;
NewNode.SelectAction = TreeNodeSelectAction.SelectExpand;
node.ChildNodes.Add(NewNode);
}
}
//Code that finds the node, and adds a new child - this is the bit not working, as it only counts 1 node
protected void btnAddCG_Click(object sender, EventArgs e)
{
int i;
i = tvTariff.Nodes.Count;
for(i=0;i < tvTariff.Nodes.Count;i++)
{
switch (tvTariff.Nodes[i].Depth)
{
case 1:
//only looking for tariff node to add a session node to
CheckTariffNode(tvTariff.Nodes[i]);
break;
}
}
}
protected void CheckTariffNode(TreeNode node)
{
if (node.Value==Session["SelectedNode"].ToString())
{
TreeNode NewNode = new TreeNode(dlTariffCG.SelectedItem.ToString(),dlTariffCG.SelectedValue.ToString());
NewNode.PopulateOnDemand = true;
NewNode.SelectAction = TreeNodeSelectAction.SelectExpand;
node.ChildNodes.Add(NewNode);
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.