Reputation: 11265
I want show text in textbox in 2 colors, for example 1 line red 2 blue, if I use name.ForeColor = Color.Red;
all text change color, but I want that will change only 1 line color.
Upvotes: 20
Views: 78871
Reputation: 3794
Use a RichTextBox for that, here is an extension method by Nathan Baulch
public static class RichTextBoxExtensions
{
public static void AppendText(this RichTextBox box, string text, Color color)
{
box.SelectionStart = box.TextLength;
box.SelectionLength = 0;
box.SelectionColor = color;
box.AppendText(text);
box.SelectionColor = box.ForeColor;
}
}
Read more here
Upvotes: 55
Reputation: 11
Here is an example with a Fontdialog and Colordialog.
void TextfarbeToolStripMenuItemClick(object sender, EventArgs e)
{
colorDialog1.ShowDialog();
richTextBox1.ForeColor = colorDialog1.Color;
listBox1.ForeColor = colorDialog1.Color;
}
void FontsToolStripMenuItemClick(object sender, EventArgs e)
{
fontDialog1.ShowDialog();
richTextBox1.Font = fontDialog1.Font;
listBox1.Font = fontDialog1.Font;
}
void HintergrundfarbeToolStripMenuItemClick(object sender, EventArgs e)
{
colorDialog1.ShowDialog();
richTextBox1.BackColor = colorDialog1.Color;
listBox1.BackColor = colorDialog1.Color;
}
Upvotes: 1
Reputation: 18069
First of all, the details + tags you provided are not sufficient - C# doesn't have one specific UI framework, it has a few: WPF, Winforms, ASP.NET, Silverlight.
Second of all, you can not do this with a regular textbox control in any of the above. You will need to find/create a custom UI control which has a different behaviour or use a more advanced control e.g. a rich text box.
Upvotes: 0
Reputation: 38079
You need to use a RichTextBox.
You can then change the textcolor by selecting text and changing the selection color or font.
richTextBox1.SelectionFont = new Font("Verdana", 12, FontStyle.Bold);
richTextBox1.SelectionColor = Color.Red;
Upvotes: 19