Dr4ken Dr4ken - 6 months ago 128
C# Question

c# delete line from textbox, and remove blank line

I have a textbox that holds file content. I have a button that when it is pressed, it deletes a line based on a string. Here is the code:

private void deleteModuleButton_Click(object sender, EventArgs e)
{
String newText = String.Empty;
List<String> lines = fileContentTextBox.Text.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList();
lines.RemoveAll(str => str.Contains(deleteModuleComboBox.Text));
lines.ForEach(str => newText += str + Environment.NewLine);
fileContentTextBox.Text = newText;
}


However, when a line is deleted it leaves a blank line at the bottom of the text box. The issue with this, is that when the file is saved. It cannot be read again because of the extra empty line. I get this error when I try to open a file that has been saved after it had a line deleted: "Additional information: Index was outside the bounds of the array". When I read the file, I take each line as string, and then split that line using "(',')".

Is there a way to change the code so that it takes "newText", and adds new lines, but not for last string? Or some other way, just so that there is no blank line at the end.

Thanks

EDIT: I got it working (Thanks L.B)

updated and working code:

private void deleteModuleButton_Click(object sender, EventArgs e)
{
String newText = String.Empty;
List<String> lines = fileContentTextBox.Text.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList();
lines.RemoveAll(str => str.Contains(deleteModuleComboBox.Text));
newText = string.Join(Environment.NewLine, lines);
fileContentTextBox.Text = newText;
}

L.B L.B
Answer Source

Replace

lines.ForEach(str => newText += str + Environment.NewLine);

with

newText = string.Join(Environment.NewLine , lines);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download