Reputation: 23
Using the richTextBox
control, how to change in real time the background color of words that are separated by a comma, and put a blank space instead of the comma? A bit like the keywords' presentation of Stackoverflow.
Upvotes: 2
Views: 3371
Reputation:
Here you have a small code red-colouring the background when certain word ("anything") is written in a richtextbox. I hope that this will be enough to help you understand how to interact with a richtextbox at runtime. Bear in mind that it is pretty simplistic: it colours "anything" only if it is first word you introduce; and stops coloring if you write any other character after it.
int lastStart = 0;
int lastEnd = 0;
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
richTextBox1.Select(lastStart, lastEnd + 1);
if (richTextBox1.SelectedText.ToLower() == "anything")
{
richTextBox1.SelectionBackColor = Color.Red;
lastStart = richTextBox1.SelectionStart + richTextBox1.SelectionLength;
}
else
{
richTextBox1.SelectionBackColor = Color.White;
}
lastEnd = richTextBox1.SelectionStart + richTextBox1.SelectionLength;
richTextBox1.Select(lastEnd, 1);
}
Upvotes: 1
Reputation: 1967
The following string: "One, Two, Three, Four" can be converted to a list of strings with the items "One" - "Two" - "Three" - "Four" with the following code:
string FullString = "One, Two, Three, Four";
Regex rx = new Regex(", ");
List<string> ListOfStrings = new List<string>();
foreach (string newString in rx.Split(FullString))
{
ListOfStrings.Add(newString);
}
Regarding the color you can take a look here: Rich Text Box how to highlight text block
To be able to do this in realtime I suggest you use the TextChanged event for the RTB and from there you can call a function changing the color. http://msdn.microsoft.com/en-us/library/system.windows.forms.control.textchanged.aspx
When this is done you can use the String.Replace(char, char)
function to remove the comas and change them to blank spaces.
http://msdn.microsoft.com/en-us/library/czx8s9ts.aspx
Upvotes: 0