Results 1 to 3 of 3

Thread: [RESOLVED] Object reference not set to an instance of an object.

  1. #1
    Junior Member
    Join Date
    Jan 12
    Posts
    23

    Resolved [RESOLVED] Object reference not set to an instance of an object.

    This is probably something really simple that I'm just over looking but when I run my code I get that error.

    My code is this:

    Code:
    Imports System.IO
    
    Partial Class _Default
        Inherits System.Web.UI.Page
        Dim news() As String 
        Dim newsID() As String
        Dim newsTitle() As String
        Dim newsBody() As String
        Dim newsAuthor() As String
        Dim i As Integer = 0
    
    
        Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
            LoadData()
            WriteData()
        End Sub
    
        Private Sub LoadData()
            Dim newsFile As String = Server.MapPath("~/App_Data/news.txt") 'set where the data is stored
    
    
            Dim srdData As System.IO.StreamReader
            srdData = New IO.StreamReader(newsFile)
    
            Dim strLine As String
    
            Do Until srdData.Peek = -1
                strLine = srdData.ReadLine
                news = strLine.Split(";")
    
                newsID(i) = news(0)
                newsTitle(i) = news(1)
                newsBody(i) = news(2)
                newsAuthor(i) = news(3)
                i += 1
            Loop
            srdData.Close()
    
        End Sub
    The content of the text file is like this:

    newsid;title;content;author

    The error occurs on the bolded line. When I look through it by debugging I see that the value of i in newsID(i) = 0 as it should and also news(0) = 1 which is what is in the text file so that's correct. So I really don't understand why I'm getting this error

    Thanks,

  2. #2
    .NUT jmcilhinney's Avatar
    Join Date
    May 05
    Location
    Sydney, Australia
    Posts
    80,867

    Re: Object reference not set to an instance of an object.

    You're declaring a bunch of array variables at the top of your page but you never actually create any arrays. To create an array you have to specify the size. As you don't know what size the array has to be you shouldn't be using arrays at all. This is exactly what collections are for. You should be using List(Of String), not String().

  3. #3
    Junior Member
    Join Date
    Jan 12
    Posts
    23

    Re: Object reference not set to an instance of an object.

    Ah ok, problem solved.

    Thanks for the help!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •