Results 1 to 10 of 10

Thread: Global Variable won't increment/decrement

  1. #1

    Thread Starter
    New Member
    Join Date
    Jan 2008
    Posts
    5

    Global Variable won't increment/decrement

    Hi all,

    I have a problem with incrementing and decrementing 'G_Index' global variable. Here is my 'default.aspx.vb' page code:

    Imports System
    Imports System.IO
    Imports System.Data

    Partial Class _Default
    Inherits System.Web.UI.Page

    Dim G_Index As Integer
    'Public Shared G_Index As Integer

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

    Protected Sub btnPrevious_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrevious.Click
    labelJobNo.Text = (Val(labelJobNo.Text) - 1).ToString
    G_Index -= 1
    MsgBox("G_Index: " + G_Index)
    End Sub

    Protected Sub btnNext_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnNext.Click
    labelJobNo.Text = (Val(labelJobNo.Text) + 1).ToString
    G_Index += 1
    MsgBox("G_Index: " & G_Index.ToString)
    End Sub
    End Class

    When I ran the page and viewed the value of 'G_Index' using MsgBox, the value only incremented once and the value stayed at 2 after a few clicking on the buttons. Why the value of global variable 'G_Index' NOT change?? Is my MS Web Developer 2008 setting has a problem?? Please pin point what is wrong with my code?

    At the moment I am using labelJobNo.Text value to act as a global value to be accessed by several buttons and subs, but I would like to be able to use G_Index as a global value.
    Any help really appreciated...

    Thank you,

  2. #2
    Smitten by reality Harsh Gupta's Avatar
    Join Date
    Feb 2005
    Posts
    2,938

    Re: Global Variable won't increment/decrement

    Because everytime your page refreshes, the value of G_Index is set to 1 in your page_load event.

    You would need to wrap it in the check condition whether page is postbacking or loading for the first time.

    vb.net Code:
    1. Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    2.  
    3. If Not Page.IsPostBack
    4.      G_Index = 1
    5. End If
    6.  
    7. End Sub
    Show Appreciation. Rate Posts.

  3. #3

    Thread Starter
    New Member
    Join Date
    Jan 2008
    Posts
    5

    Re: Global Variable won't increment/decrement

    Thanks for your respond, unfortunately I followed your suggested code and it still did not change the G_Index value, I don't know why it won't increment nor decrement?

    Thanks,

  4. #4
    Fanatic Member space_monkey's Avatar
    Join Date
    Apr 2005
    Location
    神と歩くこと
    Posts
    573

    Re: Global Variable won't increment/decrement

    Wouldn't this be a result of the stateless nature of the web? Once the server serves the page it forgets all about it, so you would have to either put the G_Index in the viewstate or store it as a hidden field on the page itself.
    Using VB6 or VB.net 2008 with .net 3.5
    "Life... death... either way I'll be confined to a small cubicle!" - Hermes Conrad

  5. #5
    Fanatic Member space_monkey's Avatar
    Join Date
    Apr 2005
    Location
    神と歩くこと
    Posts
    573

    Re: Global Variable won't increment/decrement

    Here's an example of maintaining a value across postbacks. Its not the only way but....

    vb.net Code:
    1. Private G_INDEX_NAME As String = "G_INDEX"
    2.  
    3.     Private Property G_INDEX() As Integer
    4.         Get
    5.             Return CType(ViewState.Item(G_INDEX_NAME), Integer)
    6.         End Get
    7.         Set(ByVal value As Integer)
    8.             ViewState.Item(G_INDEX_NAME) = value.ToString
    9.         End Set
    10.     End Property
    11.  
    12.     Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
    13.         G_INDEX += 1
    14.         txtResult.Text = G_INDEX.ToString
    15.     End Sub
    16.  
    17.     Protected Sub btnSub_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSub.Click
    18.         G_INDEX -= 1
    19.         txtResult.Text = G_INDEX.ToString
    20.     End Sub
    21.  
    22.     Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    23.         If Not Page.IsPostBack Then
    24.             G_INDEX = 1
    25.             txtResult.Text = G_INDEX.ToString
    26.         End If
    27.     End Sub

    wow that code highlighting can be hard on the eyes.
    Last edited by space_monkey; Jan 23rd, 2008 at 10:21 AM.
    Using VB6 or VB.net 2008 with .net 3.5
    "Life... death... either way I'll be confined to a small cubicle!" - Hermes Conrad

  6. #6
    I wonder how many charact
    Join Date
    Feb 2001
    Location
    Savage, MN, USA
    Posts
    3,704

    Re: Global Variable won't increment/decrement

    You can define your G_Index in your global.asax Application_Start event, add it to the Application bucket, and all instances of your application will share that integer value.

    Code:
    'this is Global.asax.vb
    Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
    Application.Add("G_Index", 1)
    End Sub
    
    
    'this is your page
    'something like below
    Dim r as Integer = Convert.ToInt32(Application("G_Index"))
    You can then use that variable or increment anywhere.

  7. #7

    Thread Starter
    New Member
    Join Date
    Jan 2008
    Posts
    5

    Re: Global Variable won't increment/decrement

    Hi, Thank you for your solutions Harsh, space_monkey and Nemaroller.

    First, I tried Space_monkey suggestion and it still did not change the value.

    Then, I tried Nemaroller suggestion that introduces an error as following:
    " Object reference not set to an instance of an object.
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

    Source Error:


    Line 8: 'Public Shared G_INDEX As Integer
    Line 9: 'Dim G_INDEX As Integer
    Line 10: Dim r As Integer = Convert.ToInt32(Application("G_INDEX"))
    Line 11: 'Private G_INDEX_NAME As String = "G_INDEX"
    Line 12: "

    It seems cause of the error was from "Dim r As Integer = Convert.ToInt32(Application("G_INDEX"))". I have added a 'Global.asax' to the project:
    Code:
    <%@ Application Language="VB" %>
    
    <script runat="server">
    
        Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
            ' Code that runs on application startup
            Application.Add("G_INDEX", 1)
        End Sub
        
        Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
            ' Code that runs on application shutdown
        End Sub
            
        Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
            ' Code that runs when an unhandled error occurs
        End Sub
    
        Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
            ' Code that runs when a new session is started
        End Sub
    
        Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
            ' Code that runs when a session ends. 
            ' Note: The Session_End event is raised only when the sessionstate mode
            ' is set to InProc in the Web.config file. If session mode is set to StateServer 
            ' or SQLServer, the event is not raised.
        End Sub
           
    </script>
    By the way, why didn't I get a 'Global.asax.vb' file when I add 'Global.asax' to the project? I am using MS Visual Web Developer 2008 Express Edition. At the moment I am using a Val(labelJobNo.text) to store a value of a global variable.
    Thank you all...

  8. #8
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: Global Variable won't increment/decrement

    Global.asax is not a web page to be viewed. It's simply a class, so all your code goes into global.asax.

    Place a breakpoint at

    Application.Add("G_INDEX", 1)

    And when it hits this line, press F10, then do a quick watch and evaluate Application("G_INDEX"). Anything?

    Let me further add to your confusion, though. Because it's an ASP.NET application, I recommend using static variables as they are considered more efficient. So what you can do is create a class named AppGlobals (for example) and define a static variable in it. Give it a default value, then access it from your pages using AppGlobals.VarName.

  9. #9
    I wonder how many charact
    Join Date
    Feb 2001
    Location
    Savage, MN, USA
    Posts
    3,704

    Re: Global Variable won't increment/decrement

    Since you want to actually change that value multiple times, a static member would be inappropriate.

    I think Mendhak was stating you could define a static variable name like the following so it could be used like so:
    Code:
    public class AppGlobals
    {
    public static string GINDEX = "GIndex";
    }
    
    r = Convert.ToInt32(Application(AppGlobals.GINDEX));
    Of course, doing that you sacrifice memory for having a static string that hangs around for the lifetime of the application pool and therefore can't be reclaimed until the application is torn down, whereas using
    Code:
    Application("GIndex")
    uses an instance string to do a lookup, which will be reclaimed when the method falls out of scope (or at least sometime when necessary).

    What mendhak was also NOT saying was to declare a public variable in your Global class and expect it to be inherently thread-safe. You would have to wrap accessors around it which would need to lock access to the variable from other threads while it was being manipulated. The Application cache provides that for you, so you might as well use it, unless you want further type safety.

  10. #10
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: Global Variable won't increment/decrement

    Yes, that too. :P

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width