Reputation: 10815
I have following code where I require to create the node and sub node that is to bind with the list. I am converting it to array then I am trying to add, but I fail to do this How should I do it? Following is my code:
foreach (var item in ProductCategory)
{
TreeNode tr = new TreeNode(item.CatName);
List<dataObject> lst = objFreecusatomization.GetAllCustomItems(CategoryType.Dressing, item.CategoryID);
TreeNode[] sumItemList =new TreeNode[lst.Count];
foreach (var subItem in lst)
{
sumItemList[sumItemList] = new TreeNode { Name = subItem.Name, Text = subItem.Name, Checked = subItem.Selected };
}
treeCustomItem.Nodes.Add(item.CatName, sumItemList);
}
And I also need to assign key value, name to the items being added. through LinQ or lambda-expression. What's the best way?
Upvotes: 0
Views: 2315
Reputation: 14432
This will fail: sumItemList[sumItemList] = new TreeNode ... The index of an array cannot be the array itself.
Since you have no indexer (because of the foreach) I suggest you use a List, like this:
foreach (var item in ProductCategory)
{
TreeNode treeCustomItem = new TreeNode(item.CatName);
List<dataObject> lst = objFreecusatomization.GetAllCustomItems(CategoryType.Dressing, item.CategoryID);
List<TreeNode> sumItemList = new List<TreeNode>();
foreach (var subItem in lst)
{
sumItemList.Add(new TreeNode { ... });
}
treeCustomItem.Nodes.AddRange(sumItemList.ToArray());
}
But since you're already iterating over your fetched subitems, you can also add the subitems directly instead of using an array/list. Your inner foreach would become:
foreach (var subItem in lst)
{
treeCustomItem.Nodes.Add(new TreeNode { ... });
}
Upvotes: 3