Highlight specific text in richtextbox
Asked Answered
N

2

0

I have a window form that contain a listbox and some richtextboxex. listbox contains some values. When I select any value from listbox, richtextboxex bind with data according to selected value.

I have to highlight some text which is bind to richtextbox when I select a value from listbox, e.g.:

Just a friendly reminder that you have <<OverdueInvCount>> overdue invoice(s), with an overdue balance of <<OverdueInvTotal>>. If you have any questions about the amount you owe, please give us a call and we’ll be happy to discuss it. If you’ve already sent your payment, please disregard this reminder.

All data is coming from database.

I want to highlight <<OverdueInvCount>> and <<OverdueInvTotal>> these words.

Novice answered 8/2, 2013 at 4:56 Comment(1)
Define "listbox" - such a thing occurs in many different contexts, and your tags gives no clue. Winforms, ASP.NET or something else?Goiter
C
0

Something like this should work (just tested this.. seems to work fine):

int openBrace = richTextBox.Text.IndexOf("<");
while (openBrace > -1) {
    int endBrace = richTextBox.Text.IndexOf(">", openBrace);
    if (endBrace > -1) {
        richTextBox.SelectionStart = openBrace;
        richTextBox.SelectionLength = endBrace - openBrace;
        richTextBox.SelectionColor = Color.Blue;
    }
    openBrace = richTextBox.Text.IndexOf("<", openBrace + 1);
}
Cockroach answered 8/2, 2013 at 5:15 Comment(0)
M
0

One way to do that without casting to new object with functionality you want is to override ListBox DrawItem

void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    var item = listBox1.Items[e.Index] as <Your_Item>;

    e.DrawBackground();
    if (item.fIsTemplate)
    {
        e.Graphics.DrawString(item.Text + "(Default)", new Font("Microsoft Sans Serif", 8, FontStyle.Regular), Brushes.Black, e.Bounds);
    }
    else
    {
        e.Graphics.DrawString(item.Text, new Font("Microsoft Sans Serif", 8, FontStyle.Regular), Brushes.Black, e.Bounds);
    }
    e.DrawFocusRectangle();
}

and add this in your constructor (after InitializeComponent(); call)

listBox1.DrawMode = DrawMode.OwnerDrawFixed;
listBox1.DrawItem += new DrawItemEventHandler(listBox1_DrawItem);
Monster answered 8/2, 2013 at 10:50 Comment(1)
Shouldn't it use some system variable to avoid hard coding the font? On the other hand, the Format event (msdn.microsoft.com/en-us/library/…) might be easier, since you don't have to do the drawing yourself.Goiter

© 2022 - 2024 — McMap. All rights reserved.