C#: How can I add the DATE in BOLD into a RichTextBox but keep writing in regular font (not BOLD)

StackOverflow https://stackoverflow.com/questions/21420051

  •  04-10-2022
  •  | 
  •  

Question

I have a richTextBox where a person will be reading the medical record of a patient.

I added a button that adds today's date (in DD/MM/YYYY format) into the richTextBox. When someone needs to update a patient's record, they click the button, the date is added, and they can continue typing.

I want to make the added date appear in bold. Anything typed after that should appear normally (not bold).

This is the code that adds the date:

private void button2_Click(object sender, EventArgs e)
 {
      richTextBox1.Text = richTextBox1.Text + " " +
        dateTimePicker1.Value.ToShortDateString() + ": ";
 }

(It takes the date from the dateTimePicker because this person may need to insert an older date and write down his information)

I tried using something like this:

private void button2_Click(object sender, EventArgs e)
 {
    richTextBox1.Text = = richTextBox1.Text +
        dateTimePicker1.Value.ToShortDateString() + ": ";
    richTextBox1.Font = new Font("Microsoft Sans Serif", 8, FontStyle.Bold);
    richTextBox1.ForeColor = Color.Blue;
 }

But obviously, all the other text typed afterwards is in the Blue & Bold font.

How can I add the date in bold, but have anything typed afterwards in regular font?

Was it helpful?

Solution

Tested and works:

richTextBox1.Select(richTextBox1.TextLength, 0);
richTextBox1.SelectionFont = new Font(richTextBox1.Font, FontStyle.Bold);
richTextBox1.SelectionColor = Color.Blue;

richTextBox1.AppendText(dateTimePicker1.Value.ToShortDateString());

richTextBox1.Select(richTextBox1.TextLength, 0);
richTextBox1.SelectionFont = new Font(richTextBox1.Font, FontStyle.Regular);
richTextBox1.SelectionColor = Color.Black;

richTextBox1.Focus();

OTHER TIPS

use select to do format text :

richTextBox1.Select(0, 10); // DD/MM/YYYY has 10 character
richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, FontStyle.Bold);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top