Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Winforms - Underline part of text to be displayed in textbox

Tags:

c#

winforms

I have a line of text to display and what I want to do is underline only the heading portion of the text in the display. How do I accomplish this please?

Message: This is a message for Name of Client.

Where "Message:" is underlined.

like image 658
Kobojunkie Avatar asked Dec 16 '22 23:12

Kobojunkie


2 Answers

Use RichTextBox instead !

    this.myRichTextBox.SelectionStart = 0;
    this.myRichTextBox.SelectionLength = this.contactsTextBox.Text.Length-1;
    myRichTextBox.SelectionFont = new Font(myRichTextBox.SelectionFont, FontStyle.Underline);
    this.myRichTextBox.SelectionLength = 0;
like image 143
Ahmed Ghoneim Avatar answered Dec 28 '22 11:12

Ahmed Ghoneim


You can do that underline using the RichTextBox control

  int start = rtbTextBox.Text.IndexOf("Message:", StringComparison.CurrentCultureIgnoreCase);
  if(start > 0)
  {
       rtbTextBox.SelectionStart = start;         
       rtbTextBox.SelectionLength = "Message:".Length-1;         
       rtbTextBox.SelectionFont = new Font(rtbTextBox.SelectionFont, FontStyle.Underline);
       rtbTextBox.SelectionLength = 0; 
  }

This example use directly the text you provided in your question. It will be better if you encapsulate this code in a private method and pass in the heading text.

For example:

private void UnderlineHeading(string heading)
{
    int start = rtbTextBox.Text.IndexOf(heading, StringComparison.CurrentCultureIgnoreCase);
    if(start > 0)
    {
         rtbTextBox.SelectionStart = start;         
         rtbTextBox.SelectionLength = heading.Length-1;         
         rtbTextBox.SelectionFont = new Font(rtbTextBox.SelectionFont, FontStyle.Underline);
         rtbTextBox.SelectionLength = 0; 
    }
}

and call from your form whith: UnderlineHeading("Message:");

like image 38
Steve Avatar answered Dec 28 '22 09:12

Steve