0

I got a big problem. I try to load data to listbox from a file, but when I load it I got an exception at last line of file. It says "Value cannot be null. Parameter name: item". I use this code

 ListBox2.Items.Clear() 'clear listbox2
    For i As Integer = 0 To ListBox1.Items.Count - 1
        Dim read_text As New StreamReader(ListBox1.Items.Item(i).ToString, System.Text.Encoding.GetEncoding(1250)) ' listbox1.items.item(i) is the path of file I load data from
        Try
            Do While read_text.Peek >= 0
                If read_text.ReadLine.ToString.Contains(":") Then 'dont load lines without ":" mark
                    ListBox2.Items.Add(read_text.ReadLine) 
                End If
            Loop
            read_text.Close()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    Next i

Where is the problem? Can anybody help? ;)

1
  • 2
    ReadLine() advances the file cursor. So you don't add the lines that you check. Therefore, ReadLine() can return Nothing eventually. And you must not add Nothing to the ListBox. Aug 11, 2013 at 14:06

1 Answer 1

1

The exception is thrown by ListBox.Items.Add see the MSDN documentation. You aren't allowed to add null (or nothing in VisualBasic) to the ListBox.Items

Also as written in the comment, you read one line and check it with contains, but read the next one to add it to the list.

You should change the code so that you save the line you get from ReadLine in a variable. Than check if it's not nothing and if it contains ":" - in that case you can add the variable to the ListBox2.Items.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.