Formatting first line of RichTextBox with capital letters and bold - c#

If I have a RichTextBox and want output like the first line is a font with capital letters and bold, while the next line on the contrary, what should I do?
output like this:
MY NAME IS
Diana
My address is
China

Hey try this, it works, but you might see the text flicker for a second if the user types really fast, like holding down "Enter" and etc.
private void Form_Load(object sender, EventArgs e)
{
// append the function to the RichTextBox's TextChanged event
MyRichTextBox.TextChanged += Capitalize_Bold_FirstLine;
}
private void Capitalize_Bold_FirstLine(object sender, EventArgs e)
{
RichTextBox box = sender as RichTextBox;
if (box != null && box.Text != "")
{
// get the current selection text of the textbox
int ss = box.SelectionStart;
int sl = box.SelectionLength;
// get the position where the first line ends
int firstLineEnd = box.Text.IndexOf('\n');
if (firstLineEnd < 0)
firstLineEnd = box.Text.Length;
// split the lines
string[] lines = box.Text.Split('\n');
// capitalize the first line
lines[0] = lines[0].ToUpper();
// join them back and set the new text
box.Text = String.Join("\n", lines);
// select the first line and make it bold
box.SelectionStart = 0;
box.SelectionLength = firstLineEnd;
box.SelectionFont = new Font(box.Font, FontStyle.Bold);
// select the rest and make it regular
box.SelectionStart = firstLineEnd;
box.SelectionLength = box.Text.Length - firstLineEnd;
box.SelectionFont = new Font(box.Font, FontStyle.Regular);
// go back to what the user had selected
box.SelectionStart = ss;
box.SelectionLength = sl;
}
}

Related

RichTextBox color specific line

How can I color a line in the RichTextBox which begins with a #, so like a comment in python. I have this code but it should color only the line where the # is in it. My code colors everything after one # is written:
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
string text = richTextBox1.Text;
if (richTextBox1.Lines.Contains("#") == true)
{
int firstcharindex = richTextBox1.GetFirstCharIndexOfCurrentLine();
int currentline = richTextBox1.GetLineFromCharIndex(firstcharindex);
richTextBox1.Select(firstcharindex, 10);
richTextBox1.SelectionColor = Color.Red;
richTextBox1.DeselectAll();
richTextBox1.Select(richTextBox1.Text.Length, 0);
}
}
You are missing the else condition, also do it for each line within TexBox like below
string text = richTextBox1.Text;
foreach (var line in richTextBox1.Lines)
{
if (line.Contains("#"))
{
int firstcharindex = richTextBox1.GetFirstCharIndexOfCurrentLine();
int currentline = richTextBox1.GetLineFromCharIndex(firstcharindex);
richTextBox1.Select(firstcharindex, 10);
richTextBox1.SelectionColor = Color.Red;
richTextBox1.DeselectAll();
richTextBox1.Select(richTextBox1.Text.Length, 0);
}
else
{
int firstcharindex = richTextBox1.GetFirstCharIndexOfCurrentLine();
int currentline = richTextBox1.GetLineFromCharIndex(firstcharindex);
richTextBox1.Select(firstcharindex, 10);
richTextBox1.SelectionColor = Color.Black;
richTextBox1.DeselectAll();
richTextBox1.Select(richTextBox1.Text.Length, 0);
}
}
You have to specify the richTextBox1.SelectionLength. You have to set this to your line length.
Also see: Selectively coloring text in RichTextBox

Windows form receive text input

Hey guys/girls I got myself stuck and I was hoping I could get some help with it. simply said I'm trying to make a soccerpool on windows form. Because the player can put in as many team's as he/she wants I put the code that makes the betting panels in a (for)loop with the text as 0. very handy if I say so myself but now I can't retrieve the correct input from the user or without breaking the loop. any idea's?
for (int i = 0; i < hometable.Rows.Count; i++)
{
DataRow dataRowHome = hometable.Rows[i];
DataRow dataRowAway = awayTable.Rows[i];
Label lblHomeTeam = new Label();
Label lblAwayTeam = new Label();
TextBox txtHomePred = new TextBox();
TextBox txtAwayPred = new TextBox();
lblHomeTeam.TextAlign = ContentAlignment.BottomRight;
lblHomeTeam.Text = dataRowHome["TeamName"].ToString();
lblHomeTeam.Location = new Point(15, txtHomePred.Bottom + (i * 30));
lblHomeTeam.AutoSize = true;
txtHomePred.Text = "0";
txtHomePred.Location = new Point(lblHomeTeam.Width, lblHomeTeam.Top - 3);
txtHomePred.Width = 40;
txtAwayPred.Text = "0";
txtAwayPred.Location = new Point(txtHomePred.Width + lblHomeTeam.Width, txtHomePred.Top);
txtAwayPred.Width = 40;
lblAwayTeam.Text = dataRowAway["TeamName"].ToString();
lblAwayTeam.Location = new Point(txtHomePred.Width + lblHomeTeam.Width + txtAwayPred.Width, txtHomePred.Top + 3);
lblAwayTeam.AutoSize = true;
pnlPredCard.Controls.Add(lblHomeTeam);
pnlPredCard.Controls.Add(txtHomePred);
pnlPredCard.Controls.Add(txtAwayPred);
pnlPredCard.Controls.Add(lblAwayTeam);
So what my end goal is, is recieving the input from the user validating them and then storing them in a database.
Well, depending on how the user activates an event that requires the reading of the TextBox you have a few possible solutions.
Here is one where the TextBox (read all TextBox's) waits for enter:
private void Form_Load(object sender, EventArgs e)
{
while(someLoop)
{
TextBox theTextBox = new TextBox();
theTextBox.Name = "SomeUniqeName";//Maybe team name?
theTextBox.KeyUp += TheTextBox_KeyUp;
}
}
private void TheTextBox_KeyUp(object sender, KeyEventArgs e)
{
if ( e.KeyCode == Keys.Enter )
{
TextBox textbox = (TextBox) sender;//Get the textbox
//Just an example
listOfTeams.First( r => r.TeamName == textbox.Name )
.SomeOtherProperty = textbox.Text;
}
}
The textbox's are now identifiable by their name and all have an event. No matter how many you make.
If you will store the data later with 1 click of a button (and another loop) this solution might be better:
string[] Teams = { "teamA", "teamB", "teamC" };
private void Form1_Load(object sender, EventArgs e)
{
for ( int i = 0; i < Teams.Length; i++ )
{
TextBox theTextBox = new TextBox();
//Prefix the name so we know this is a betting textbox
//Add the 'name' (teams[i] in this case) to find it
theTextBox.Name = "ThePrefix" + Teams[i];
}
}
private void someButton_Click(object sender, EventArgs e)
{
//We want all betting textbox's here but also by team name
for ( int i = 0; i < Teams.Length; i++ )
{
//Because we set the name, we can now find it with linq
TextBox textBox = (TextBox) this.Controls.Cast<Control>()
.FirstOrDefault( row => row.Name == "ThePrefix" + Teams[i] );
}
}
This way each textbox is identifiable and won't conflict with other textbox's (because of 'ThePrefix'). This is essentially the other way around from the first method as it looks for the textbox based on data rather than data based on textbox name.

Changing character colour from input

I'm trying to change the colour of a character if the input from the text box matches the one in the rich text box.
char key = e.KeyChar;
for(int i = 0; i < rchtxtbox.Text.Length; i++)
{
char currentLetter = rchtxtbox.Text[i];
if (key == currentLetter)
{
rchtxtbox.SelectionStart = 0;
rchtxtbox.SelectionLength = 1;
rchtxtbox.SelectionColor = Color.White;
rchtxtbox.SelectionBackColor = Color.LightGreen;
}
}
It only highlights the current letter if it does matches. An example is if the word in the rich text box is "balloon" and the input first typed is "b", it matches and changes colour but if the next letter was added "ba" the function stops working and does not change colour. Other alternatives I have tried ended up changing the colours of all matched characters. I want to be able to colour it character by character if it matches, is there a way to do this easily?
Ok, here's how you can achieve this. I have used KeyUp event instead of keypress
private void textBox1_KeyUp(object sender, KeyEventArgs e) {
if (textBox1.TextLength == 0) { return; }
int index;
index = textBox1.TextLength - 1;
char key = textBox1.Text[index];
if (rchtxtbox.TextLength > index && rchtxtbox.Text[index] == key) {
if (rchtxtbox.Text[index] == key) {
rchtxtbox.SelectionStart = index;
rchtxtbox.SelectionLength = 1;
rchtxtbox.SelectionColor = Color.White;
rchtxtbox.SelectionBackColor = Color.LightGreen;
}
}
}
Make sure you replace textBox1 above with the name of your textbox
If I am understanding your questions correctly, the issue is just that you are only ever selecting the first character for highlight.
You should be setting SelectionStart to i, so it selects and highlights the character you are comparing against:
rchtxtbox.SelectionStart = i;
Edit:
After thinking about what you're trying to do, I think you have a rich text box with text in it. You also have a text box that the user is typing into. As the user types into the text box, you want to highlight that text in the rich text box. Correct?
Here is a simple example, although this doesn't account for multiple occurrences of the text being found.
private void textBox1_TextChanged(object sender, EventArgs e)
{
int idx = richTextBox1.Text.IndexOf(textBox1.Text);
if (idx > -1)
{
richTextBox1.SelectionStart = idx;
richTextBox1.SelectionLength = textBox1.Text.Length;
richTextBox1.SelectionColor = Color.White;
richTextBox1.SelectionBackColor = Color.LightGreen;
}
}

Color specific words in RichtextBox

How can I make, that when the user types specific words like 'while' or 'if' in a rich textbox, the words will color purple without any problems? I've tried diffrent codes, but none of them were usable. The codes were like below:
if (richTextBox.Text.Contains("while"))
{
richTextBox.Select(richTextBox.Text.IndexOf("while"), "while".Length);
richTextBox.SelectionColor = Color.Aqua;
}
Also, I want that when the user removes the word or removes a letter from the word, the word will color back to its default color. I'm making a program with a code editor in it.
I am using Visual c#.
Thank you.
Add an event to your rich box text changed,
private void Rchtxt_TextChanged(object sender, EventArgs e)
{
this.CheckKeyword("while", Color.Purple, 0);
this.CheckKeyword("if", Color.Green, 0);
}
private void CheckKeyword(string word, Color color, int startIndex)
{
if (this.Rchtxt.Text.Contains(word))
{
int index = -1;
int selectStart = this.Rchtxt.SelectionStart;
while ((index = this.Rchtxt.Text.IndexOf(word, (index + 1))) != -1)
{
this.Rchtxt.Select((index + startIndex), word.Length);
this.Rchtxt.SelectionColor = color;
this.Rchtxt.Select(selectStart, 0);
this.Rchtxt.SelectionColor = Color.Black;
}
}
}
This is something that you can do, I would recommend using a regular expression to find all matches of the word in case it occurs many times. Also keep in mind that the string find could be a list of strings out side of a for loop to consider multiple words but this should get you started.
//dont foget to use this at the top of the page
using System.Text.RegularExpressions;
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
string find = "while";
if (richTextBox1.Text.Contains(find))
{
var matchString = Regex.Escape(find);
foreach (Match match in Regex.Matches(richTextBox1.Text, matchString))
{
richTextBox1.Select(match.Index, find.Length);
richTextBox1.SelectionColor = Color.Aqua;
richTextBox1.Select(richTextBox1.TextLength, 0);
richTextBox1.SelectionColor = richTextBox1.ForeColor;
};
}
}
You can use richTextBox1_KeyDown event
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
{
String abc = this.richTextBox1.Text.Split(' ').Last();
if (abc == "while")
{
int stIndex = 0;
stIndex = richTextBox1.Find(abc, stIndex, RichTextBoxFinds.MatchCase);
richTextBox1.Select(stIndex, abc.Length);
richTextBox1.SelectionColor = Color.Aqua;
richTextBox1.Select(richTextBox1.TextLength, 0);
richTextBox1.SelectionColor = richTextBox1.ForeColor;
}
}
}
If instead of a word you want to highlight a regular expression, you can use this:
private void ColorizePattern(string pattern, Color color)
{
int selectStart = this.textBoxSrc.SelectionStart;
foreach (Match match in Regex.Matches(textBoxSrc.Text, pattern))
{
textBoxSrc.Select(match.Index, match.Length);
textBoxSrc.SelectionColor = color;
textBoxSrc.Select(selectStart, 0);
textBoxSrc.SelectionColor = textBoxSrc.ForeColor;
};
}

RichTextBox text color

I created RichTextBox and I add this code:
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
//( )
int selectionStart = richTextBox1.SelectionStart;
string helpText = richTextBox1.Text;
int closerPos;
for (int i = 0; i < helpText.Length; i++)
{
if (helpText[i] == '(')
{
selectionStart = richTextBox1.SelectionStart;
closerPos = helpText.Substring(i).IndexOf(')') + i;
helpText = helpText.Substring(i + 1, closerPos - i - 1);
richTextBox1.Text = richTextBox1.Text.Remove(i + 1, closerPos - i - 1);
richTextBox1.Select(i + 1, 0);
richTextBox1.SelectionColor = Color.Red;
richTextBox1.SelectedText = helpText;
richTextBox1.SelectionColor = Color.Black;
helpText = richTextBox1.Text;
richTextBox1.SelectionStart = selectionStart;
}
}
}
This code should color the text between the ( ).
For example:
"Hi (need to be colored) text (sdadsasd) "
the text between the ( ) need to be colored in red. but only the last text is colored. How can I fix it?
You're only getting the first paranthesis with that if condition.
Try splitting the text like helpText.Split('(');
Then iterate over it and do your logic.
I think you can accomplish this without moving byte by byte. You can try to do it using the IndexOf method.
This is something I was thinking of:
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
string rbText = richTextBox1.Text;
int position = 0;
int startBrace = rbText.IndexOf('(', position) + 1;
while (startBrace != -1)
{
position = rbText.IndexOf(')', startBrace);
if (position != -1)
{
richTextBox1.Select(startBrace, position - startBrace);
richTextBox1.SelectionColor = Color.Red;
startBrace = rbText.IndexOf('(', position) + 1;
}
else
break;
}
}
Keep in mind that I haven't fully test this code.
I already see a potential issue, helpText is being used as an array when it is only a single-variable string. Try breaking the entirety of helpText down into a char array, then iterating through that to find your brackets.

Categories