开发者

how to work treeview nodes contains in asp.net?

开发者 https://www.devze.com 2023-02-25 00:56 出处:网络
these codes are not working. how to add only one value. i can not use .Nodes.Contains method.For example : my customer:

these codes are not working. how to add only one value. i can not use .Nodes.Contains method.For example : my customer: yusuf1, yusuf2,yusuf1, yusuf4; i see treeview yusuf1, yusuf2,yusuf1, yusuf4;. But i want t开发者_JAVA百科o see yusuf1, yusuf2, yusuf4

   protected void FillTreeViewCustomers()
        {
            MyClass mytest = new MyClass ();
            IEnumerable<Quotation> mytestList = mytest .GetAll();
            foreach MyClass item in mytestList )
            {
                            
                TreeNode newnode = new TreeNode() { Text = item.Customer, Value = item.Customer };
                if (!treeViewCustomer.Nodes.Contains(newnode))
                {
                    treeViewCustomer.Nodes.Add(newnode);
                }
               

            }
        }


The problem with treeViewCustomer.Nodes.Contains(newnode) is that this method checks for reference equality only. You cannot use it to determine whether an equivalent but different node is in the collection.

There are a few options available to you however, such as doing a foreach loop to look for matching nodes, or by assigning a unique key to the treenode when you add it, and using the .ContainsKey method. I think TreeNodeCollection uses Name as the Key.

So, in your example - something like this should do it

if (!treeViewCustomer.Nodes.ContainsKey(item.Customer)
{
   treeViewCustomer.Nodes.Add(new TreeNode { 
     Name=item.Customer, 
     Text=item.Customer, 
     Value=item.Customer 
   });
}


@Programmerist: The problem is how TreeNode.Contains compares the nodes while searching the TreeNodeCollection. I had this problem as well, and decided to do a foreach on the collection to compare fields manually.

Obs: remember that there two differente but similar types of tree nodes

    System.Windows.Forms.TreeNode
    System.Web.UI.WebControls.TreeNode


Is this a copy of your code or a freehand expression?

In your example you're creating a collection of items called "mytestList" but then use "quotationList" in your foreach loop.

Also, you code is missing:

treeViewCustomer.DataBind();

Are you doing this elsewhere?


The line if (!treeViewCustomer.Nodes.Contains(newnode)) will always be true because the object that it's checking the collection for has just been created.

If you want to avoid adding an equivalent node, you need to alter the way that you're checking the collection.

0

精彩评论

暂无评论...
验证码 换一张
取 消