I have a program which needs to determine the number of lines in a multiline textbox to know how to process it. I am calling the TextBox.Lines.Length property, which was working. Now however, no matter how many lines of text are visible in the GUI, this value is 1, and all of the "\r\n" strings have disappeared from the TextBox.Text string. Any Ideas? My code is as following :
TextBox.MultiLine = true;
TextBox.WordWrap = true;
for (int i = 0; i < TextBox.Lines.Length - 1; i++)
//Some Code
As I said in the comment, with Multiline=True and WordWrap=True, your textbox will display a long line as multilines (Wrapped)... but actually it is one single line, and that's why your Lines.Length=1, try type in some line break yourself, and test it again. Or you can set WordWrap=False, and you will see there is only one line...
It will need to be marked as multiline, check that, you can parse like so:
string txt = TextBox1.Text;
string[] lst = txt.Split(new Char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries)
Related
private void Parse_Click(object sender, EventArgs e)
{
for (int i = 0; i < keywordRanks.Lines.Length; i++)
{
int p = keywordRanks.Lines.Length;
MessageBox.Show(p.ToString());
string splitString = keywordRanks.Lines[i];
string[] s = splitString.Split(':');
for (int j = 0; j < keywords.Lines.Length; j++)
{
string searchString = keywords.Lines[j];
if (s[0].Equals(searchString))
{
richTextBox1.Lines[j] = searchString + ':' + s[1];
}
}
}
}
I have an issue with inserting string in a particular line. I have 2 multi line TextBoxes and one RichTextBox.
My application will search for the strings from textbox1 to textbox2 line by line and need to insert those matched values in a RichTextBox control but in the exact index position where it found in textbox2.
If the value found in 5th line of textbox2 then that found line need to be inserted in the RichTextBox 5th line.
Some how my code is not working. I tried a lot but no luck. The code I need something like below but its not working and an IndexOutOfBound exception is raised.
richTextBox1.Lines[j] = searchString + ':' + s[1];
Your RichTextBox must contain all the needed lines before you can set the value using the line index.
If the Control contains no text or line breaks (\n), no lines are defined and any attempt to set a specific Line[Index] value will generate an IndexOutOfRangeException exception.
Here, I'm using a pre-built array, sized as the number of possible matches (the Lines.Length of the keywords TextBox). All matches found are stored here in the original position. The array is then assigned to the RichTextBox.Lines property.
Note: directly using and pre-setting the RichTextBox.Lines won't have effect: the text will remain empty.
string[] MatchesFound = new string[keywords.Lines.Length];
foreach (string currentSourceLine in keywordRanks.Lines)
{
string[] SourceLineValue = currentSourceLine.Split(':');
var match = keywords.Lines.ToList().FindIndex(s => s.Equals(SourceLineValue[0]));
if (match > -1)
MatchesFound[match] = currentSourceLine;
}
richTextBox1.Lines = MatchesFound;
Source Matches Result
(keywordRanks) (keywords) (RichTextBox)
-------------------------------------------
aand:1 aand aand:1
cnd:5 this one
cnds:9 cnds cnds:9
fan:2 another one
gst:0 cnd cnd:5
fan fan:2
I am unable to Change the specific string of a multiline TextBox.
suppose first line of multiline textbox is "Hello" & second line is "Bye".But when i trying to change the value of second line like below.
textBox1.Lines[1] = "Good bye";
When I saw the result using Debug mode it was not "Good bye".
I also read this MSDN article & this stackoverflow question but can't get the desired answer.
As MSDN states (the link you provided):
By default, the collection of lines is a read-only copy of the lines in the TextBox.
To get a writable collection of lines, use code
similar to the following: textBox1.Lines = new string[] { "abcd" };
So, you have to "take" Lines collection, change it, and then return to TextBox. That can be achieved like this:
var lines = TextBox1.Lines;
lines[1] = "GoodBye";
TextBox1.Lines = lines;
Alternatively, you can replace text, like Wolle suggested
First you need assign textBox1.Lines array in variable
string[] lines = textBox1.Lines;
Change Array Value
lines[1] = "Good bye";
Reassign array to text box
textBox1.Lines=lines;
According to MSDN
By default, the collection of lines is a read-only copy of the lines
in the TextBox. To get a writable collection of lines need to assign
new string array
Working with TextBox lines via Lines property are extremely ineffective. Working with lines via Text property is a little better, but ineffective too.
Here the snippet, that allows you to replace one line inside TextBox without rewriting entire content:
public static bool ReplaceLine(TextBox box, int lineNumber, string text)
{
int first = box.GetFirstCharIndexFromLine(lineNumber);
if (first < 0)
return false;
int last = box.GetFirstCharIndexFromLine(lineNumber + 1);
box.Select(first,
last < 0 ? int.MaxValue : last - first - Environment.NewLine.Length);
box.SelectedText = text;
return true;
}
You could try to replace the text of second line like this:
var lines = textBox.Text.Split(new[] { '\r', '\n' }).Where(x => x.Length > 0);
textBox.Text = textBox.Text.Replace(lines.ElementAt(1), "Good bye");
I have a list of strings stored in an ArrayList. I want to split them by every occurrence of ';'. The problem is, whenever I try to display them using MessageBox, there's an excess space or unnecessary value that gets displayed.
Sample input (variable = a):
Arial;16 pt;None;None;None;None;None;None;FF0000;None;100;Normal;None;Normal;
Below is a line of code I used to split them:
string[] display_document = (a[0] + "").Split(';');
Code to display:
foreach (object doc_properties in display_document)
{
TextBox aa = new TextBox();
aa.Font = new Font(aa.Font.FontFamily, 9);
aa.Text = doc_properties.ToString();
aa.Location = new Point(pointX, pointY);
aa.Size = new System.Drawing.Size(80, 25);
aa.ReadOnly = true;
doc_panel.Controls.Add(aa);
doc_panel.Show();
pointY += 30;
}
The output that displays are the following:
How do I remove the last occurrence of that semicolon? I really need help fixing this. Thank you so much for all of your help.
Wouldnt It be easiest to check if the input ends with a ";" before splitting it, and if so remove the last character? Sample code:
string a = "Arial;16 pt;None;None;None;None;None;None;FF0000;None;100;Normal;None;Normal;";
if (a.EndsWith(";"))
{
a = a.Remove(a.LastIndexOf(";"));
}
//Proceed with split
Split will not print last semicolon if no space character is added and your input is a string.
I don't know why you prefer an array list (which probably is the reason of this strange behaviour) but if you could use your input as a string you could try that
string a = "Arial;16pt;None;None;None;None;None;None;FF0000;None;100;Normal;None;Normal;";
string[] display_document = a.Split(';');
foreach (object doc_properties in display_document)
{
//The rest of your code
}
I'm trying to replace pipe symbol(|) with new line(\n) in my text(test1.txt) file. But when I'm trying to save it in text(test2.text) file the result is not coming in my test2.txt file but I see the result in my console window. Any one please help on this.
string lines = File.ReadAllText(#"C:\NetProject\Nag Assignments\hi.txt");
//string input = "abcd|efghijk|lmnopqrstuvwxyz";
lines = lines.Replace('|', '\n');
File.WriteAllText(#"C:\NetProject\Nag Assignments\hi2.txt", lines);
Console.WriteLine(lines);
You can try this one:
lines = lines.Replace("|", Environment.NewLine);
It returns "\r\n", for non-Unix platforms according to documentation.
Seems like you want multiple things here. (both original question and subsequent comments)
One is to separate the lines and be able to reference them separately:
string[] separatedLines = lines.Split('|');
The other is to join them back together with a different separator:
string rejoinedLines = string.Join(Environment.NewLine, separatedLines);
You then have access to the individual lines from the separatedLines variable above such as separatedLines[0] and you can also write the rejoinedLines variable back to the other file like you wanted.
EDIT: For example, the following code:
string lines = "a|bc|def";
string[] separatedLines = lines.Split('|');
string rejoinedLines = string.Join(Environment.NewLine, separatedLines);
for (int i = 0; i < separatedLines.Length; i++)
{
Console.WriteLine("Line {0}: {1}", i + 1, separatedLines[i]);
}
Gives output of:
Line 1: a
Line 2: bc
Line 3: def
Instead of:
lines = lines.Replace('|', '\n');
Try:
lines = lines.Replace("|","\r\n");
string[] space = lines.Split ('|');
Will save every substring in space.
The line break should be \r\n for carriage return. It depends if you are reading a file binary or text mode. \n is used in text mode while \r\n is used in binary mode.
I have a list of lines that looks like this:
textbox.text += "p"+b+" the rest\r\np"+b+" more text";
b is supposed to represent the current line number in the textbox that the line is on. I have tried using textbox.lines.count() but it only changes i into the last line number.
Is there any other way about going with this, or do I have to switch to another method?
If you are assigning, I think you can do it manually (calculate the line number). There is no function that could "guess" on which line the tex will appear.
You can create a integer variable and increment it when appending a line/s and use the variable when you need to display the current line number.
I split the lines by the line breaks ("\r\n") and used a for loop to replace "b" (I changed it to string rather than a variable)
for (int i = 0; i < da.Length; i++)
{
//replace char with number
string f = da[i].Replace("n", (i + 1).ToString());
disp.Text += f + "v";
}
I added "v" so that I can replace it outside of the loop with "\r\n" again.