Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Highlighting text in a textbox 1

Status
Not open for further replies.

SlantyOD

Programmer
Jun 11, 2002
22
0
0
CA
Hi all,

Does anybody know offhand how to highlight certain text in a textbox(or richtextbox)? I'm trying to compare two strings that are 100,000 chars long (using String.Compare) and if they're different I'd like to know how they're different.

What I'd like to do is compare the strings one char at a time and add them to a textbox, and then highlight them based on whether they were the same or different as the other string. By highlight I mean bold, italics, in french, I don't care as long as they stick out =). Performance isn't an issue, this is for my reference only.

Alternately if someone knows an easier way to find the exact differences between two strings that would be great as well =).

Thanks in advance,
SlantyOD
 
I haven't done this, but I'm thinking you need to keep two copies of your text. One in the "background" that is just text, and another loaded in a RTF control, that has all the formatting codes in it. Whenever you search for something, you'd do the search on the background copy, and for every "hit", you'd do something like:

While (bFound) {
bFound = FindHit(characters to hit on);
RTFCopy.Append(characters up to the hit)
RTFCopy.Append("RTFBold")
RTFCopy.Append(hit characters)
RTFCopy.Append("RTFNormalText")
}
RTFControl.Rtf = RTFCopy;

Chip H.
 
Thanks ChipH, you gave me the clues that I needed. I ended up doing it this way:

for (int x = 0; x < txtString1.Length; x++)
{
int z = string.Compare(txtString1, x, txtString2, x, 1)
if (z == 0)
{
RichTextBox.AppendText(txtString1.Substring(x, 1));
}
else
{
RichTextBox.SelectionFont = new Font(&quot;Ariel&quot;, 12, FontStyle.Bold);
RichTextBox.AppendText(txtString1.SubString(x, 1));
RichTextBox.SelectionFont = new Font(&quot;Ariel&quot;, 12, FontStyle.Regular);
}
}

I'm still pretty new at C# so if anybody has any suggestions as to how to do this better I'd love to hear them. I really like to keep my code as clean as possible.

Cheers,
SlantyOD

PS, for the record, this method takes a long time to get through 100,000 characters =).
 
SlantyOD -

This might be a good opportunity to load your code into the performance test tool to see where the bottleneck is. I suspect it'll be in the string.Compare(), but it might be interesting to see if that's the case.

Chip H.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top