Search code examples
c#richtextboxrtf

How to selectively underline strings in RichTextBox?


In my program after clicking on the button - selected ListView entries should be copied to RichTextBox. ListView contains contact information, and the effect I want to accomplish is similar to the one in Oultook (when choosing contacts from contact book). Part of my code that serves this purpose looks like that:

    private void toButton_Click(object sender, EventArgs e)
    {
        int start = 0;
        for (int i = 0; i < contactsListView.SelectedItems.Count; i++)
        {
            if (contactsTextBox.TextLength != 0) contactsTextBox.Text += "; ";
            start = contactsTextBox.TextLength;
            contactsTextBox.Text += contactsListView.SelectedItems[i].Text + " " + contactsListView.SelectedItems[i].SubItems[1].Text + " [" + contactsListView.SelectedItems[i].SubItems[2].Text + "]";
            contactsTextBox.Select(start, contactsTextBox.TextLength);       
            contactsTextBox.SelectionFont = new Font(contactsTextBox.SelectionFont, FontStyle.Underline);
            contactsTextBox.DeselectAll();
            contactsTextBox.SelectionFont = new Font(contactsTextBox.SelectionFont, FontStyle.Regular);
        }
    }

Unfortunately somehow FontStyle is inherited by entire text and everything I enter after entry from ListView is also underlined.

So my question is - how to underline only certain text (where I have made a mistake)?

There is similar topic on stackoverflow here unfortunately in my case solution stated there will be waste of resources.


Solution

  • Try this instead:

            int start = 0;
            for (int i = 0; i < contactsListView.SelectedItems.Count; i++)
            {
                if (contactsTextBox.TextLength != 0) contactsTextBox.Text += "; ";
                start = contactsTextBox.TextLength;
                contactsTextBox.Text += contactsListView.SelectedItems[i].Text +" " + contactsListView.SelectedItems[i].SubItems[1].Text + " [" + contactsListView.SelectedItems[i].SubItems[2].Text + "]";
            }
    
    
            this.contactsTextBox.Text += " ";
            this.contactsTextBox.SelectionStart = 0;
            this.contactsTextBox.SelectionLength = this.contactsTextBox.Text.Length-1;
            contactsTextBox.SelectionFont = new Font(contactsTextBox.SelectionFont, FontStyle.Underline);
            this.contactsTextBox.SelectionLength = 0;
    

    Total hack, but basically, if you select the text after it's all there, but don't select ALL of it (which is why I add the extra " ") and then set the selection text, it has the desired effect.