开发者

VB.net global variable doesn't work right?

开发者 https://www.devze.com 2023-03-29 15:56 出处:网络
I have a problem with a global variable in VB.Net. In one sub (triggered by a button) I create objects and store them into a global variable (an array).After that I create a table (DataGrid).

I have a problem with a global variable in VB.Net.

In one sub (triggered by a button) I create objects and store them into a global variable (an array). After that I create a table (DataGrid).

With a second button another sub is triggered and tries to use the array from the global variable, but it seems to be empty.

Here is the code:

<script runat="server">
    Dim array_datensatz(12) As Datensatz

    Sub submit1_click(ByVal Sender As Object, ByVal E As EventArgs)
        Dim cellX As New TableCell()

        For n = 0 To 12 '13 objects a created
            Dim tmpklasse As New Datensatz(n)
            array_datensatz(n) = tmpklasse

            ' MsgBox(tmpklasse.methode_merkmal1) ' method_merkmal1 returns a Integer
            ' MsgBox(array_datensatz(n).methode_merkmal1())   'both work
        Next n

        ItemsGrid.DataSource = CreateDataSource()   'creates table
        ItemsGrid.DataBind()
    End Sub

    Function CreateDataSource() As ICollection
        Dim dt As New DataTable()
        Dim dr As DataRow

        dt.Columns.Add(New DataColumn("Merkmal1"))
        dt.Columns.Add(New DataColumn("Merkmal2"))
        dt.Columns.Add(New DataColumn(开发者_如何学JAVA"Merkmal3"))

        Dim i As Integer

        For i = 0 To (array_datensatz.GetLength(0) - 1)   'länge des array der ergebnise (0. dim) = #results

            dr = dt.NewRow()
            dr(0) = array_datensatz(i).methode_merkmal1()
            dr(1) = array_datensatz(i).methode_merkmal2()
            dr(2) = array_datensatz(i).methode_merkmal3()
            dt.Rows.Add(dr)
        Next i

        Dim dv As New DataView(dt)

        Return dv
    End Function 'CreateDataSource

    Public Sub sub_anonym(ByVal Sender As Object, ByVal E As EventArgs)
        For i = 0 To (array_datensatz.GetLength(0) - 1)   
            MsgBox(array_datensatz(i).methode_merkmal1()) 'throws an exception saying that ~"the object reference doesn't target an object-instance"
        Next i
    End Sub

</script>

What is the problem? Why arn't the objects in the array?


This is in a website?

If so, the user clicking the second button creates another request. The variable you're saving to isn't saved between requests, so it's not there anymore (as it was set on the first request, which is now completed). To preserve values like that across multiple requests you'll need to use a way of storing them that lasts longer, such as a Session.

0

精彩评论

暂无评论...
验证码 换一张
取 消