0

i just new to aspx.net

i try to call array variable from aspx.vb but problem occured

Object reference not set to an instance of an object.

here the code in aspx.vb :

Imports System.Data.OleDb
Partial Class MasterPage Inherits System.Web.UI.MasterPage

Public count() As String
Public Location() As String
Public m As Integer = 1
Public i As Integer = 1

Public Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    Dim connectString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
                                "Data Source=" & Server.MapPath("db1.mdb")

    Dim cn As OleDbConnection = New OleDbConnection(connectString)

    cn.Open()

    Dim selectString As String = "SELECT * FROM Landslides"
    Dim cmd As OleDbCommand = New OleDbCommand(selectString, cn)
    Dim reader As OleDbDataReader = cmd.ExecuteReader()



    While (reader.Read())

        count(m) = reader("Bil").ToString
        Location(m) = reader("Location").ToString
        m += 1
    End While


End Sub

code on aspx :

<% For i = 1 To m Step 1 %>

    <li><br /><a href='Second.aspx?id='> <%Response.Write(Location(m))%> </a></li>
                                <%Next%>

when i try to compile result is fine . but when i try to load the website there will be error . i am using visual studio 2005

Rahul Singh
  • 21,585
  • 6
  • 41
  • 56
ZackRich
  • 3
  • 1
  • 2
  • Check if `reader("Bil")` is `null`. you are directly invoking `ToString()` method which will throw a null reference exception if `reader("Bill")` is null. – Rahul Singh Jan 16 '15 at 04:57
  • yeah already check it. its not null . but i try change the error line like this count(0) = "hello" the error is still there – ZackRich Jan 16 '15 at 07:37
  • Duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Bjørn-Roger Kringsjå Jan 16 '15 at 13:24

1 Answers1

0

You are incrementing value of m after you have added an entry in array hence when wile loop will end your array will be one length shorter than value of m. So when you try to access last value from array you get this error. Assign m with value of 0 and incrment before you add entry in array.

Public m As Integer = 0

And change while loop like this

While (reader.Read())
    m += 1  
    count(m) = reader("Bil").ToString
    Location(m) = reader("Location").ToString

End While
Mairaj Ahmad
  • 14,434
  • 2
  • 26
  • 40
  • i already changed it but still, same problem occurs. Object reference not set to an instance of an object. on code - count(m) = reader("Bil").ToString – ZackRich Jan 16 '15 at 04:40