Ilham Nasution Ilham Nasution - 1 year ago 332
C# Question

How to remove lines one by one in Richtextbox C#

I use this code to delete lines one by one in richtextbox, but still leaving an empty line (whitespace).

var text = "";//Holds the text of current line being looped.
var startindex = 0;//The position where selection starts.
var endindex = 0;//The length of selection.

for (int i = 0; i < richtextbox1.Lines.Length; i++)//Loops through each line of text in RichTextBox
text = richtextbox1.Lines[i]; //Stores current line of text.

startindex = richtextbox1.GetFirstCharIndexFromLine(i);
endindex = text.Length;
richtextbox1.Select(startindex, endindex);
richtextbox1.SelectedText = "";

How do I delete lines one by one without empty lines (whitespace)?

Answer Source
// Gets the number of newline characters in your rich text box
var numberOfNewLines = richTextBox1.Text.Count(r => r == '\n');

for (var i = 0; i < numberOfNewLines; i++)
     // Finds the first occurance of the newline character
     var newlineCharacterIndex = richTextBox1.Text.IndexOf('\n') + 1;

     // Replaces the rich textbox text with everything but the above line
     richTextBox1.Text = richTextBox1.Text.Substring(newlineCharacterIndex);


// Removes the final line.
richTextBox1.Text = string.Empty;

I think you were on the right track, but the way you were doing it was just removing the contents of the line and not the line itself.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download