How to remove lines from string which has nothing except a blank newline?

I have two TextBoxes in my form with Multiline enabled and a Button. Lets say tB1 and tB2. tB1 and tB2 consist group numbers and the Button click event removes all the string (numbers) from the tB1 that are present on tB2. But as all the numbers are being separated by NewLine replacing the string by matching with with another string causes a lots of blank lines between.

Example -tB1 Values:

1

2

3

4

5

6

7

8

9

10

Example -tB2 Values:

3

7

8

What I am getting:

1

2

[Blank Line]

4

5

6

[Blank Line]

[Blank Line]

9

10

What I want it to be:

1

2

4

5

6

9

10

I am using the code:

Dim strFix() as String

Private Sub Button1_Click() Handles Button1.Click
    strFix = Split(tB2.Text, vbNewLine)
    For Each str1 as String In strFix
        tb1.Text= tb1.Text.Replace(str1, "")
    Next
End Sub

Note: Using .Trim() didn't solved this as it only removes the last blank lines or spaces.

Upvotes: 0

Views: 1622

Answers (4)

Muhammad
Muhammad

Reputation: 1350

txtResult.Lines = txtSource.Lines.Where(Function(line) line.Trim() <> String.Empty).ToArray()

Upvotes: 0

BuddyRoach
BuddyRoach

Reputation: 162

I think this is happening because of the For Each loop. It is "doubling up" this code each time it cycles through an item.

Upvotes: 0

I have found a solution that worked for me.

Dim strFix() As String

Private Sub FixBlankLines ()
    strFix = Split(tB2.Text, vbNewLine)
    For Each str1 as String In strFix
        tb1.Text= tb1.Text.Replace(str1, "")
    Next
    strFix = Split(tb1.Text, vbNewLine)
    tb1.Text = ""
    For Each str2 As String In strFix
        If str2 <> "" Then
             tb1.Text += Val(str2).ToString("00000") + vbNewLine
        End If
    Next
    tb1.Text = tb1.Text.Trim
End Sub

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460208

String.Replace doesn't help to remove those lines. You have to create a new line-list without those which appear in Tb2.

You can use TextBox.Lines to get an array of all lines. LINQ simplifies the task:

Dim onlyInTb1 = tB1.Lines.Except(tB2.Lines)
tB1.Lines = onlyInTb1.ToArray()

The classic non-LINQ way is to use a List(Of String):

Dim onlyInTb1List As New List(Of String)
Dim tb2Lines = tb2.Lines
For Each tb1Line In tB1.Lines
    If Not tb2Lines.Contains(tb1Line) 
        onlyInTb1List.Add(tb1Line)
    End If
Next
tb1.Lines = onlyInTb1List.ToArray()

Finally an approach without the textBox.Lines-"trick" with String.Split and String.Join:

Dim tb1Lines = tB1.Text.Split({Environment.NewLine}, StringSplitOptions.None)
Dim tb2Lines = tB2.Text.Split({Environment.NewLine}, StringSplitOptions.None)
Dim onlyInTb1 = tb1Lines.Except( tb2Lines )
tB1.Text = String.Join(Environment.NewLine, onlyInTb1)

Upvotes: 4

Related Questions