Search code examples
stringvb.nettrim

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.


Solution

  • 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