Reputation: 124
I want to make part of the text bold in a textbox, for example the textbox contains.
"This is a text box"
So it will be "This is a text box"
How can I do it in C# Windows Forms?
Upvotes: 2
Views: 15664
Reputation: 171
You can do this with the help of FontStyle
interface.
Just add a button in your form and name it Bold and create a click event for that.
You have to use RichTextBox
for this, you cannot do this with TextBox
.
This code will convert the selected text to bold.
private void btnBold_Click(object sender, EventArgs e)
{
FontStyle style = tbMessage.SelectionFont.Style;
if (tbMessage.SelectionFont.Bold)
{
style = style & ~FontStyle.Bold;
btnBold.Font = new Font(btnBold.Font, FontStyle.Regular);
}
else
{
style = style | FontStyle.Bold;
btnBold.Font = new Font(btnBold.Font, FontStyle.Bold);
}
tbMessage.SelectionFont = new Font(tbMessage.SelectionFont, style);
tbMessage.Focus();
}
Upvotes: 1
Reputation: 112259
To be clear, you cannot do that in a TextBox
. Use a RichTextBox
.
In a RichTextBox
, start by selecting the desired text by setting the SelectionStart
and the SelectionLength
properties or let the user select text interactively. Then apply a formatting by setting one of the Selection...
properties:
richTextBox1.Text = "This is a text box";
richTextBox1.SelectionStart = 5;
richTextBox1.SelectionLength = 2;
richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, FontStyle.Bold);
Upvotes: 0
Reputation: 6202
You cannot do it in a standard TextBox control, you need to use a RichTextBox control with appropriate formatting.
Upvotes: 0