ASP.net array doesn't hold values

Hi

I have declared an arrau at the top of the code behind my webform (see code below)
As I assign different values to the array after my Gridview is declared, the rest of the array values seem to clear. Not sure why this is happening.


Dim arrSuccess(19) As String 'holds successful entry data

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

Open in new window

Murray BrownMicrosoft Cloud Azure/Excel Solution DeveloperAsked:
Who is Participating?
 
CartaUserConnect With a Mentor Commented:
this is the expected behaviour as the asp.net pages ar stateless. you need to store that variable in viewstate etc, then nexttime you need to fecth it from viewstate.

Exemple :

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


  ' Sample ArrayList for the page.
  Dim arrSuccess As ArrayList

  Function CreateArray() As ArrayList
    ' Create a sample ArrayList.
    Dim result As ArrayList
    result = New ArrayList(4)
    
    result.Add("item 1")
    result.Add("item 2")
    result.Add("item 3")
    result.Add("item 4")
    
    Return result
  End Function
  
  Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    If (Me.ViewState("arrayListInViewState") IsNot Nothing) Then
      PageArrayList = CType(Me.ViewState("arrayListInViewState"), ArrayList)
    Else
      ' ArrayList isn't in view state, so we need to load it from scratch.
      PageArrayList = CreateArray()
    End If
    ' Code that uses PageArrayList.
  End Sub
  
  Sub Page_PreRender(ByVal sender As Object, ByVal e As EventArgs)
    ' Save PageArrayList before the page is rendered.
    Me.ViewState.Add("arrayListInViewState", PageArrayList)
  End Sub

Open in new window

0
 
DotTechnologiesCommented:
Can you provide the complete code?
0
 
CartaUserCommented:
Hi murbro,

An ASP.NET page class file is destroyed after it is served to the client.

The most chosen method for preserving variables in ASP.NET from one page
load to the next is to store them in viewstate which is a hidden input:

ViewState("arrSuccess") = ....

You could use viewstate or session objects to persist items.

Session("arrSuccess") = ....

for more information : http://msdn.microsoft.com/en-gb/magazine/cc300437.aspx
0
 
Murray BrownMicrosoft Cloud Azure/Excel Solution DeveloperAuthor Commented:
No. Sorry. Have deleted it and reverted to using labels to hold my values. Any general information felating to why an array would lose its values on postback would help. Thanks
0
 
Murray BrownMicrosoft Cloud Azure/Excel Solution DeveloperAuthor Commented:
Great. Thank you very much for the help
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.