从后面的代码调用数组变量

时间:2015-01-16 04:08:33

标签: asp.net vb.net

我刚接触aspx.net

我尝试从aspx.vb调用数组变量但出现问题

对象引用未设置为对象的实例。

这里是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

aspx上的代码:

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

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

当我尝试编译结果很好。但是当我尝试加载网站时会出现错误。我正在使用visual studio 2005

1 个答案:

答案 0 :(得分:0)

在数组中添加条目后,您正在递增m的值,因此当wile循环结束时,数组将比m的值短一个长度。因此,当您尝试从数组访问最后一个值时,您会收到此错误。在数组中添加条目之前,为m赋值为0和incrment。

Public m As Integer = 0

并像这样改变循环

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

End While