Problem with ArrayList

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nadaNuaim
    New Member
    • Feb 2007
    • 8

    Problem with ArrayList

    I have an arraylist and i define it as public variable

    Public StockArray As New ArrayList

    inside button1_click body
    i append new elements in that Stockarray
    by
    dim stockobj as new stock // stock is a class

    StockArray.Add( stockobj)

    when i print any element of Stockarray within button1 body it works fine

    but when i call the stockArray in a another button body the StockArray is empty !


    any ideas will be Extremly helpful
  • SammyB
    Recognized Expert Contributor
    • Mar 2007
    • 807

    #2
    Originally posted by nadaNuaim
    I have an arraylist and i define it as public variable

    Public StockArray As New ArrayList

    inside button1_click body
    i append new elements in that Stockarray
    by
    dim stockobj as new stock // stock is a class

    StockArray.Add( stockobj)

    when i print any element of Stockarray within button1 body it works fine

    but when i call the stockArray in a another button body the StockArray is empty !


    any ideas will be Extremly helpful
    Are you sure you placed StockArray in the correct place? Works for me:
    Code:
    Public Class Form1
    	Public StockArray As New ArrayList
    	Public iCounter As Integer = 0
    	Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    		iCounter = iCounter + 1
    		Dim s As New Stock
    		s.ID = "A-" & iCounter
    		StockArray.Add(s)
    		ListStock()
    	End Sub
    	Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    		iCounter = iCounter + 1
    		Dim s As New Stock
    		s.ID = "B-" & iCounter
    		StockArray.Add(s)
    		ListStock()
    	End Sub
    	Private Sub ListStock()
    		Dim s As Stock, msg As String = ""
    		For Each s In StockArray
    			msg = msg & s.ID & ", "
    		Next
    		msg = Strings.Left(msg, Len(msg) - 2)
    		MsgBox("ArrayList contains " & msg)
    	End Sub
    End Class
    Public Class Stock
    	Public ID As String
    End Class

    Comment

    • channaJ
      New Member
      • Mar 2007
      • 67

      #3
      Originally posted by nadaNuaim
      I have an arraylist and i define it as public variable

      Public StockArray As New ArrayList

      inside button1_click body
      i append new elements in that Stockarray
      by
      dim stockobj as new stock // stock is a class

      StockArray.Add( stockobj)

      when i print any element of Stockarray within button1 body it works fine

      but when i call the stockArray in a another button body the StockArray is empty !


      any ideas will be Extremly helpful
      Hi,

      Is it a web application you are working on? If it is so, I think the problem is caused by the postback. When you do a postback from the first button click,
      Code:
      Public StockArray As New ArrayList
      will be called again and it will create a new empty StockArray object. You can use the following code to instanciate the StockArray only in the initial page load.
      Code:
      if(!IsPostback)
      Public StockArray As New ArrayList
      Hope this will help.

      Comment

      • nadaNuaim
        New Member
        • Feb 2007
        • 8

        #4
        thanks alot SammyB but this is exactly my problem the buttons ommit each other changes


        and YES channaJ i'm using a web application i'm interested in your sollution

        but shall I declare StockArray only once in the page_load ? because when I did the buttons could not see StockArray declaration!

        and it force me to replace
        Code:
         
        If (Not IsPostBack) Then
        Public StockArray as new ArrayList 
        End IF
        with this
        Code:
         
        If (Not IsPostBack) Then
        Dim StockArray as new ArrayList 
        End IF
        and when I declare StockArray inside the body of Page_Load and inside the body of page Class the Array became empty :)

        I'm So sorry but I'm new to asp.net with VB

        Comment

        • SammyB
          Recognized Expert Contributor
          • Mar 2007
          • 807

          #5
          > I'm So sorry but I'm new to asp.net with VB
          You are better than I, I've never created a web form, so Chan will have to help you there.

          But, notice where I defined StockArray. It is inside the Form class, but outside of all of the Sub's. Thus, there is just one of them and all of the Sub's can access it. You should have a similar structure in your code.

          Comment

          • nadaNuaim
            New Member
            • Feb 2007
            • 8

            #6
            Originally posted by channaJ
            Hi,

            Is it a web application you are working on? If it is so, I think the problem is caused by the postback. When you do a postback from the first button click,
            Code:
            Public StockArray As New ArrayList
            will be called again and it will create a new empty StockArray object. You can use the following code to instanciate the StockArray only in the initial page load.
            Code:
            if(!IsPostback)
            Public StockArray As New ArrayList
            Hope this will help.
            *************** ********
            Hello channaJ,

            I did exactly what you siad but declaring StockArray as an ArrayList inside the page_load makes StockArray undeclared to other subs inside the page calss

            as you siad when not post back the array contents will be empty ,i checked that by printing the array count (StockArray.Cou nt) and the result is zero :(

            what should i do i need the array to save pervious valuse of stocks and use them when Undoing last changes.

            thanks in advance

            Comment

            • nadaNuaim
              New Member
              • Feb 2007
              • 8

              #7
              Hello every body

              can any one help me with this issue i waste lots of time on it but still could not find the right sullotion any ideas :) !

              regards

              Comment

              • Frinavale
                Recognized Expert Expert
                • Oct 2006
                • 9749

                #8
                Originally posted by nadaNuaim
                I have an arraylist and i define it as public variable

                Public StockArray As New ArrayList

                inside button1_click body
                i append new elements in that Stockarray
                by
                dim stockobj as new stock // stock is a class

                StockArray.Add( stockobj)

                when i print any element of Stockarray within button1 body it works fine

                but when i call the stockArray in a another button body the StockArray is empty !


                any ideas will be Extremly helpful
                Hi there!

                When creating a web application you have to remember that every time the user clicks a button (or causes a postback event) its as if they are coming to the website for the first time.

                In your case, you're creating the stockArray ArrayList, but you are only filling it within the method that handles your button click event. Once that information is sent back to the user, all the objects are destroyed.

                There is never a persistent connection to the user and the application.

                This means that when the user does something else that causes a postback a new stockArray (ArrayList) is created.

                In order to use information collected from a previous postback to the website you need to store your arrayList in a persistent data store....like Session.

                (please note that my code is in VB.NET and is just a guideline...it probably wont work)
                Code:
                Private stockArray As ArrayList
                
                Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load, Me.Load
                
                    'Since this is executed first every time we fill our stockArray 
                    'variable with what ever is in the Session from previous visits
                    'this way we can use it in the subs that handle the events
                
                    stockArray = new ArrayList
                
                    Try
                        stockArray=CType(Session("arrayListInStore"),ArrayList)
                
                        If stockArray Is Nothing
                             'This is the case when the user is first visiting the website or the
                             'Session has expired and there is no arrayList stored in session
                   
                            stockArray = new ArrayList
                   
                             'here fill your stock array with default values if you'd like
                        End If
                     Catch ex As Exception
                
                     End Try
                
                End Sub
                
                Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
                    'Here you can fill the stockArray Array list but make sure that you
                    'Store this in session so that you can use this data later
                
                     'I always double check to make sure the object has been intialized
                      If stockArray Is Nothing Then
                        stockArray = new ArrayList
                     End IF
                
                     stockArray.Add(....)
                    Session("arrayListInStore")=stockArray
                
                End Sub
                
                
                Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
                    'Since you've already filled the stockArray variable in the page_load method
                    'with the information gathered during the Button1 postback (which was 
                    'stored in session)...
                    'You will be able to use the information in the stockArray variable in
                    'this method
                
                     lbl_output.Text = stockArray.Length.ToString()
                
                End Sub

                Does this make sense?

                (Oh yeah, you don't need to make the variable Public unless its being used by another object. I'd recommend making it Private if its not being used by another object)

                Cheers

                -Frinny

                Comment

                • nadaNuaim
                  New Member
                  • Feb 2007
                  • 8

                  #9
                  pew! Finally i found it instead of declaring StockArray as public or dim declare it as shared
                  thanks Chan and Sammy for your time and effort :)

                  here is the code
                  Code:
                   
                  
                      Shared StockArray As New ArrayList
                  
                   '***********************************************************'
                      Public Sub Update_Group(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
                          'Loop through each DataGridItem, and determine which CheckBox controls
                          'have been selected.
                  
                  
                          Dim GridItem As DataGridItem
                          For Each GridItem In DataGrid1.Items
                  
                              Dim myCheckbox As CheckBox = CType(GridItem.Cells(0).Controls(1), CheckBox)
                              Dim TextBox1 As TextBox = CType(GridItem.Cells(4).Controls(1), TextBox)
                              Dim TextBox2 As TextBox = CType(GridItem.Cells(5).Controls(1), TextBox)
                  
                              If myCheckbox.Checked = True Then
                  
                                  Dim Stockobj As New stock
                                  Stockobj.FunCode = DataGrid1.DataKeys(GridItem.ItemIndex).ToString()
                                  Stockobj.FunPrice = Convert.ToDouble(TextBox1.Text)
                                  Stockobj.FunVolume = Convert.ToInt64(TextBox2.Text)
                                  StockArray.Add(Stockobj)
                                  '  Response.Write(Stockobj.FunCode)
                                  ' rowCount += 1
                                  DoUpdateStock(DataGrid1.DataKeys(GridItem.ItemIndex).ToString(), Convert.ToDouble(TextBox1.Text), Convert.ToInt64(TextBox2.Text))
                              End If
                          Next
                          updateDate.Text = "Last Update was on " & Now()
                  
                  
                          BindDataGrid()
                      End Sub
                  
                  
                  
                      Public Sub Undo_Update(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.Click
                  
                          Dim i As Integer = 0
                  
                          While (i < StockArray.Count - 1)
                          
                              DoUpdateStock(StockArray(i).FunCode, StockArray(i).FunPrice, StockArray(i).FunVolume)
                              i += 1
                          End While
                  
                          updateDate.Visible = False
                  
                          BindDataGrid()
                  
                      End Sub

                  Comment

                  • nadaNuaim
                    New Member
                    • Feb 2007
                    • 8

                    #10
                    Originally posted by Frinavale
                    Hi there!

                    When creating a web application you have to remember that every time the user clicks a button (or causes a postback event) its as if they are coming to the website for the first time.

                    In your case, you're creating the stockArray ArrayList, but you are only filling it within the method that handles your button click event. Once that information is sent back to the user, all the objects are destroyed.

                    There is never a persistent connection to the user and the application.

                    This means that when the user does something else that causes a postback a new stockArray (ArrayList) is created.

                    In order to use information collected from a previous postback to the website you need to store your arrayList in a persistent data store....like Session.

                    (please note that my code is in VB.NET and is just a guideline...it probably wont work)
                    Code:
                    Private stockArray As ArrayList
                    
                    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load, Me.Load
                    
                        'Since this is executed first every time we fill our stockArray 
                        'variable with what ever is in the Session from previous visits
                        'this way we can use it in the subs that handle the events
                    
                        stockArray = new ArrayList
                    
                        Try
                            stockArray=CType(Session("arrayListInStore"),ArrayList)
                    
                            If stockArray Is Nothing
                                 'This is the case when the user is first visiting the website or the
                                 'Session has expired and there is no arrayList stored in session
                       
                                stockArray = new ArrayList
                       
                                 'here fill your stock array with default values if you'd like
                            End If
                         Catch ex As Exception
                    
                         End Try
                    
                    End Sub
                    
                    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
                        'Here you can fill the stockArray Array list but make sure that you
                        'Store this in session so that you can use this data later
                    
                         'I always double check to make sure the object has been intialized
                          If stockArray Is Nothing Then
                            stockArray = new ArrayList
                         End IF
                    
                         stockArray.Add(....)
                        Session("arrayListInStore")=stockArray
                    
                    End Sub
                    
                    
                    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
                        'Since you've already filled the stockArray variable in the page_load method
                        'with the information gathered during the Button1 postback (which was 
                        'stored in session)...
                        'You will be able to use the information in the stockArray variable in
                        'this method
                    
                         lbl_output.Text = stockArray.Length.ToString()
                    
                    End Sub

                    Does this make sense?

                    (Oh yeah, you don't need to make the variable Public unless its being used by another object. I'd recommend making it Private if its not being used by another object)

                    Cheers

                    -Frinny
                    --------------------------

                    Hi Firnny

                    you know i have read lots of articles talking about session I'll try your code coze the code i have solves some problems not all of them

                    thanks

                    Comment

                    Working...