Add Selected nodes of a treeview to a ListBox

Ndebata
Posted by Ndebata under ASP.NET category on | Points: 40 | Views : 5559
Add Selected nodes of a treeview to a ListBox

Here my aspx page has three conrols (Treeview,button and a Listbox)
The body of my aspx is

<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<asp:TreeView ID="TreeView1" runat="server" ShowCheckBoxes="All" >
</asp:TreeView>
</td>
<td>
<asp:Button ID="Button1" runat="server" Text=" Move " onclick="Button1_Click" />
</td>
<td>
<asp:ListBox ID="ListBox1" runat="server" Width="200" ></asp:ListBox>
</td>
</tr>
</table>
</div>
</form>
</body>

The Code behind file

public partial class TreeListBox : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
PopolateTreeView();
}
private void PopolateTreeView()
{
TreeNode pnode= new TreeNode("All Group1", "1");
for (int i = 0; i < 3; i++)
{
TreeNode chnode = new TreeNode("GRP1TEM" + i);
pnode.ChildNodes.Add(chnode);
}
TreeView1.Nodes.Add(pnode);
pnode = new TreeNode("All Group2", "1");
for (int i = 0; i < 4; i++)
{
TreeNode chnode = new TreeNode("GRP2TEM" + i);
pnode.ChildNodes.Add(chnode);
}
TreeView1.Nodes.Add(pnode);
}
protected void Button1_Click(object sender, EventArgs e)
{
List<TreeNode> lstselected=new List<TreeNode>();
foreach (TreeNode parent in TreeView1.Nodes)
{
if (parent.Checked && parent.ChildNodes.Count > 0)
lstselected.AddRange(parent.ChildNodes.Cast<TreeNode>());
else
lstselected.AddRange(parent.ChildNodes.Cast<TreeNode>().Where(n => n.Checked));
}
ListBox1.Items.AddRange(lstselected.Select(l => new ListItem(l.Text, l.Value)).ToArray<ListItem>());
foreach (TreeNode item in lstselected)
{
for (int i = 0; i < TreeView1.Nodes.Count; i++)
{
TreeView1.Nodes[i].ChildNodes.Remove(item) ;
}
var EmptyNodes = TreeView1.Nodes.Cast<TreeNode>().Where(n => n.ChildNodes.Count == 0).ToList<TreeNode>();
foreach (var pn in EmptyNodes)
{
TreeView1.Nodes.Remove(pn);
}
}
}
}

Thanks,
Debata

Comments or Responses

Posted by: T.saravanan on: 5/2/2011 Level:Silver | Status: [Member] [MVP] | Points: 10
Hi Ndebata,

Don't assign 'i' as variable in for loop because in our website brace of 'i' is consider about italic format.
So check your code and change that variable.

Login to post response