0

I have a treeview with nodes.I am implementing searching through treeview nodes .Once matching node is find ,the node color should be changed .it is working fine ,but the problem is while searching for a new node the previously searched node color is also changed . Any help will be really appreciated .Thanks in advance.

protected void btn_search_Click(object sender, EventArgs e)
   {
       try
       {
           FindNodesByString();

       }

       catch { }
   }

   private void FindNodesByString()
   {
       foreach (TreeNode currentNode in tv_AccountView.Nodes)
       {
           FindNodeByString(currentNode);
       }
   }

   private void FindNodeByString(TreeNode parentNode)
   {
       FindMatch(parentNode);
       foreach (TreeNode currentNode in parentNode.ChildNodes)
       {
           //currentNode.Text = currentNode.Text;
           FindMatch(currentNode);
           FindNodeByString(currentNode);
       }
   }
  private void FindMatch(TreeNode currentNode)
   {
       if (currentNode.Text.ToUpper().Contains(txt_searchbyname.Text.ToUpper()))
       {
           currentNode.Expand();
           currentNode.Text = "<div style='background- 
           color:#ffffcc;color:#ff9900;'>" + currentNode.Text + " 
          </div>";

       }
       else
       {
           currentNode.Text = currentNode.Text;
           // currentNode.Collapse();
         //  currentNode.ShowCheckBox = false;
       }
   }
Ann Sara
  • 59
  • 1
  • 7
  • Isn’t it so the previous node still has the color because you have never reset the color? – Aldert Aug 22 '18 at 18:42

1 Answers1

0

You are setting the node's text to html with color after it is found. You never remove the html when it is not found.

   else
   {
       currentNode.Text = currentNode.Text; //need to remove the HTML tags (if any) here
       // currentNode.Collapse();
     //  currentNode.ShowCheckBox = false;
   }

To accomplish removing the HTML you could:

  • Use what this answer suggests, or look through the other answers.
  • If you have the original source of the text you could grab it from there.
  • You could store the original text in a dictionary with the node as the key, then look it back up to reset it.

To do the simple regex way, it would look like this:

   else
   {
       //remove the HTML tags (if any) here
       currentNode.Text = Regex.Replace(currentNode.Text, "<.*?>", String.Empty);
       // currentNode.Collapse();
     //  currentNode.ShowCheckBox = false;
   }
TheSoftwareJedi
  • 34,421
  • 21
  • 109
  • 151