That's because you are setting the color with a
div
element. Once that's been rendered in the client/browser, it will remain there. Your
else
block of your code will still hold the
Text
with the
<div>
element to it. You would need to implement a bit of text parsing to resolve that.
Here's a quick demo:
ASPX:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:TreeView ID="TreeView1" runat="server">
<Nodes>
<asp:TreeNode Text="Vincent">
<asp:TreeNode Text="Vynn" />
<asp:TreeNode Text="Vianne" />
</asp:TreeNode>
<asp:TreeNode Text="Maverick" />
</Nodes>
</asp:TreeView>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</form>
</body>
</html>
CODE BEHIND:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
namespace WebFormDemo
{
public partial class TreeView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e) {
}
protected void Button1_Click(object sender, EventArgs e) {
bool found = false;
foreach (TreeNode node in TreeView1.Nodes) {
found = IsNodeMatch(node, TextBox1.Text);
if (!found) {
foreach (TreeNode childNode in node.ChildNodes) {
found = IsNodeMatch(childNode, TextBox1.Text);
}
}
}
if (!found)
Response.Write("Search did not match anything.");
}
private bool IsNodeMatch(TreeNode node, string searchText) {
if (node.Text.ToLower().Equals(searchText.ToLower())) {
node.Text = string.Format("<div style='color:#ff9900' >{0}</div>", node.Text);
return true;
}
else {
node.Text = ParseText(node.Text);
}
return false;
}
private string ParseText(string text) {
string pattern = "<div(.*?)>(.*?)</div>";
var regex = new Regex(pattern);
var match = regex.Match(text);
if (match.Length > 0)
return match.Groups[2].Value;
return text;
}
}
}
The key there is the
ParseText()
that is used within the
else
block to trim down the
div
element.