c# how can I update just one line text in richtextbox? - c#

how can I update just one line text in richtextbox?
String[] lines = richTextBox8.Lines;
lines[2] += " ";
richTextBox8.Lines = lines;
I am using this code part for update second line of richtextbox but it scans all my richtextbox lines and it takes many times.
so I want to update line text for 1 line.
How can I do that?

Note that you must never touch the Text or the Lines directly or all previous formatting gets messed up.
Here is a function that will solve the problem without messing up the formatting:
void changeLine(RichTextBox RTB, int line, string text)
{
int s1 = RTB.GetFirstCharIndexFromLine(line);
int s2 = line < RTB.Lines.Count() - 1 ?
RTB.GetFirstCharIndexFromLine(line+1) - 1 :
RTB.Text.Length;
RTB.Select(s1, s2 - s1);
RTB.SelectedText = text;
}
Note the in C# the numbering is zero beased, so to change the 1st line you call changeLine(yourrichTextBox, 0, yourNewText);
To only modify (not replace) the line you can simply access the Lines property; just make sure never to change it!
So to add a blank to the 2nd line you can write:
changeLine(yourrichTextBox, 1, yourrichTextBox.Lines[1] + " ");

Related

String.IndexOf function giving incorrect position number for TextBox.Select

I found a strange behavior in indexOf functionality in my code, My string input is from read from a text file, when I search some text in the firstline of the code indexOf function correctly identify the position of the sub-string, but if I search some text in the second line it returns one character after the exact match, if I search something in the 3rd line it is returning 2 character position after the exact match, this is changing in the same pattern with every new line. I don't know why this is happening, I need to find a way to get the exact same position of the text.
My Code:
string fileContent = File.ReadAllText(filename);
string display_string = "";
txtOriginalText.Text = fileContent;
HighlightText(fileContent.IndexOf("projection"), 5, Color.Aqua);
display_string += fileContent.IndexOf("projection").ToString() + '\n';
HighlightText(fileContent.IndexOf("component"), 5, Color.LightGreen);
display_string += fileContent.IndexOf("component").ToString() + '\n';
HighlightText(fileContent.IndexOf("layer"), 5, Color.Pink);
display_string += fileContent.IndexOf("layer").ToString() + '\n';
txtModifiedText.Text = display_string;
Highlight function
private void HighlightText(int startIndex, int textLength, Color state)
{
txtOriginalText.Select(startIndex, textLength);
txtOriginalText.SelectionBackColor = state;
}
Image:
I tested this with a RichTextBox:
richTextBox1.Text = "test\r\ntest\r\ntest\r\n";
When you debug and check richTextBox1.Text after that line, its value is "test\ntest\ntest\n".
So it seems the RichTextBox removes the \r from your string (which as a Windows file content probably contains new line characters as \r\n).
As an immediate work around you should use IndexOf on txtOriginalText.Text instead of fileContent.

RichTextbox write in place to current line

Clarification: I want to output line of text to the same "position" in a RichTextBox, replacing the previous line.
In C# Windows Forms Application trying to use RichTextBox for displaying messages. Most of the messages are appended, so that is fine but at one point in the program it has a counter, showing the amount of rows processed. For example like this:
Processed: 001 Records.
etc
well ... I don't need it to fill the RichTextBox with a thousands of lines like this:
Processed: 001 Records.
Processed: 002 Recoeds.
Instead I am trying to move the Caret to a start of the line and write the line again. Probably need to remove the previous line in a RichTextBox. Can't figure out how to always write to the same last line in RichTextBox.
I tried to use SelectionStart and ScrollToCaret() that did not work.
You could try something like this (rtb is your RichTextBox variable)
// Get the index of the last line in the richtextbox
int idx = rtb.Lines.Length - 1;
// Find the first char position of that line inside the text buffer
int first = rtb.GetFirstCharIndexFromLine(idx);
// Get the line length
int len = rtb.Lines[idx].Length;
// Select (Highlight) that text (from first to len chars)
rtb.SelectionStart = first;
rtb.SelectionLength = len;
// Replace that text with your update
rtb.SelectedText = "Processed: " + recordCount + " Records.";
No error handling added, but you could add some checks to be sure to stay inside the text buffer
One solution would be to store the current text before you start processing:
string oldText = richTextBox.Text;
for (int i = 0; i < X; i++)
{
// process stuff
richTextBox.Text = oldText + Environment.NewLine + "Processed: " + i + " Records.";
}
I believe that this method disregards the RTF data though, so you might use RichTextBox.Rtf instead.

Word count not working when entering new line

I've been looking at other stack overflow articles regarding similar issues when it comes to word count in C#, but none have helped me when it comes to the pickle I've encountered.
I have a textbox that inputs text from a text file. The text is split into three lines by me pressing the enter button to create a new line in a text file. The text reads:
It's a test to see "if" the
application_for Top Image Systems
actually work. Hopefully it does work.
Now as you can see there should be 17 words, however my word count only says 15. I have realized after a bit of trial and error that the issue must be the fact it's in a new line. Every time it goes to a new line, it thinks the last word of the previous line and the first word of the new line are together as a word (or that's what I think the program is thinking).
My question is with the code I have below, how can I get to recognize that if there is a new line, that it should split the words like a space?
Below is my code:
string nl = System.Environment.NewLine;
//Missing Code to read text file which I don't need to include in this example
do
{
textLine = textLine + txtReader.ReadLine();
}
//Read line until there is no more characters
while (txtReader.Peek() != -1);
//seperate certain characters in order to find words
char[] seperator = (" " + nl).ToCharArray();
//number of words
int numberOfWords = textLine.Split(seperator, StringSplitOptions.RemoveEmptyEntries).Length;
txtReader.ReadLine(); strips your newline away.
From the msdn:
The string that is returned does not contain the terminating carriage return or line feed.
so you have to add it manually (or just add a space)
textLine = textLine + txtReader.ReadLine() + " ";
consider using the StringBuilder class for repeated concatination of strings.
Edit:
To get the character count as if the spaces were never added, do:
int charCount = textLine.Length - lineCount;
where lineCount an integer that you increment every time you add a space in your do-while loop:
int lineCount = 0;
do
{
textLine = textLine + txtReader.ReadLine();
lineCount++;
}
I'm a bit of a beginner myself, sorry if this is not a great answer, but I've just done a bunch of text stuff in c# and I'd probably approach by replacing the line breaks which will show up as "\n" or "\r" in your original string with a space, " " - something like:
nl = nl.Replace("\r", " ");

RichTextBox SelectionStart offset with linebreaks

I'm using a RichTextBox for coloured text. Let's assume I want to use different colours for different portions of the text. This is working fine so far.
I'm currently having a problem with the SelectionStart property of the RichTextBox. I've set some text to the Text property of the RichTextBox. If the text contains \r\n\r\n the SelectionStart Position won't match the position of characters with the assigned String.
Small example (WinformsApplication. Form with a RichTextBox):
public Form1()
{
InitializeComponent();
String sentence1 = "This is the first sentence.";
String sentence2 = "This is the second sentence";
String text = sentence1 + "\r\n\r\n" + sentence2;
int start1 = text.IndexOf(sentence1);
int start2 = text.IndexOf(sentence2);
this.richTextBox1.Text = text;
String subString1 = text.Substring(start1, sentence1.Length);
String subString2 = text.Substring(start2, sentence2.Length);
bool match1 = (sentence1 == subString1); // true
bool match2 = (sentence2 == subString2); // true
this.richTextBox1.SelectionStart = start1;
this.richTextBox1.SelectionLength = sentence1.Length;
this.richTextBox1.SelectionColor = Color.Red;
this.richTextBox1.SelectionStart = start2;
this.richTextBox1.SelectionLength = sentence2.Length;
this.richTextBox1.SelectionColor = Color.Blue;
}
The RichTextBox looks like this:
As you can see, the first two characters of the second sentence are not coloured. This is the result of an offset produced by \r\n\r\n.
What is the reason for this? Should I use another control for colouring text?
How do I fix the problem in a reliable way? I've tried replacing the "\r\n\r\n"with a String.Empty, but that produces other offset problem.
Related question:
Inconsistent behaviour between in RichTextBox.Select with SubString method
It seems that the sequence \r\n counts for one character only when doing selections. You can do the measurements in a copy of the string where all \r\n are replaced by \n.
Just for completeness (I'll stick to linepogls answer for now):
I've found another way to get indices for the SelectionStart property. The RichTextBox offers a Find method, that can be used to retrieve index positions based on a specified string.
Be aware of the fact, that the text you want to highlight might not be unique and occur multiple times. You can use an overload to specify a start position for the search.

winforms big paragraph tooltip

I'm trying to display a paragraph in a tooltip when I hover a certain picture box. The problem is, the tooltip takes that paragraph, and spans it on one line, all across my screen. How can I make it so that it takes a smaller, more readable area?
or, maybe you have another technique to achieve the same thing, but without the tooltip function?
Add line breaks to your string.
string tooltip = string.Format("Here is a lot of text that I want{0}to display on multiple{0}lines.", Environment.NewLine);
You don't need to use code to include \r\n characters.
If you click on the dropdown arrow to the right of the ToolTip property value, it displays a multiline edit box.
Just press Enter to create a new line.
Here's something you can use:
private const int maximumSingleLineTooltipLength = 20;
private static string AddNewLinesForTooltip(string text)
{
if (text.Length < maximumSingleLineTooltipLength)
return text;
int lineLength = (int)Math.Sqrt((double)text.Length) * 2;
StringBuilder sb = new StringBuilder();
int currentLinePosition = 0;
for (int textIndex = 0; textIndex < text.Length; textIndex++)
{
// If we have reached the target line length and the next
// character is whitespace then begin a new line.
if (currentLinePosition >= lineLength &&
char.IsWhiteSpace(text[textIndex]))
{
sb.Append(Environment.NewLine);
currentLinePosition = 0;
}
// If we have just started a new line, skip all the whitespace.
if (currentLinePosition == 0)
while (textIndex < text.Length && char.IsWhiteSpace(text[textIndex]))
textIndex++;
// Append the next character.
if (textIndex < text.Length)
sb.Append(text[textIndex]);
currentLinePosition++;
}
return sb.ToString();
}
Have you tried inserting newlines \n into the tooltip, to get it to span multiple lines?
You can't add the \r\n in the tooltip property of the control. It simply doesn't work. To resolve you issue, simply add the tooltip in the code itself typically in the InitializeComponent method.
I.E.: (c#, winform example)
this.mToolTip.SetToolTip(this.tbxControl,
"This is the first line of the tooltip.\r\n" +
"This is the second line of the tooltip.");
Using new line worked for me
System.Environment.NewLine
If you enter a tool tip in the DataGridView properties control for columns, and I suspect other WinForms control designers, and include a "\r\n" in the tool tip, you will see "\\r\\n" in the tool tip that is displayed when you run the code. This is because the tool tip property is already a string, and the designer interprets the code from the tool tip entered in the properties window as "\\r\\n". You can go to the .Designer.cs file, manually edit the file, and replace "\\r\\n" with "\r\n". You will then see the tool tip with the line break when the application runs. If you go back and look at the value of the tool tip in the designer, you will see the tool tip without the line break, but it will be there, and will not be re-transformed to "\\r\\n" by the designer. Despite a comment made earlier, you only need the "\n". The "\r" is not necessary.

Categories