ASP.net variables declared at top of web form

Hi. I have declared two variables at the top of my web form

    Dim xSQLAdapter_Periods As SqlDataAdapter
    Dim xSQLTable_Periods As New DataTable

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

I need to use these variables in the code behind the webform several times while the page is running but am worried about whether they will hold their values. I have noticed that variables seem to lose their values after a post back. Should they hold or should I use a different approach?
Murray BrownMicrosoft Cloud Azure/Excel Solution DeveloperAsked:
Who is Participating?
 
Obadiah ChristopherCommented:
Globally declaring the variables will hold the values.
0
 
Alan WarrenApplications DeveloperCommented:
Hi murbro,
Partial Class Default4
  Inherits System.Web.UI.Page
  Private mintSomeID As Int32 = 0

  Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
    Response.Write(mintSomeID.ToString())
  End Sub
End Class

Open in new window

Alan
0
 
Alan WarrenApplications DeveloperCommented:
hi murbro,
apologies, there was an error in my previous post.
The following won't be available to other pages, but will be available to other script blocks within the same class or partial class; and definitely survives postbacks.
<%@ Page Language="VB" %>

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

<script runat="server">
  Protected Shared mintSomeID As Int32

  Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then
      mintSomeID = 0
    Else
      Label1.Text = mintSomeID.ToString()
    End If

  End Sub

  Protected Sub PostbackButton_Click(sender As Object, e As System.EventArgs)
    mintSomeID += 1
  End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
  <form id="form1" runat="server">
    <div>
      <asp:Button ID="PostbackButton" runat="server" Text="Postback" 
        onclick="PostbackButton_Click" />
      <br /><asp:Label ID="Label1" runat="server" Text=""></asp:Label>    
    </div>
    </form>
</body>
</html>

Open in new window

Alan
0
 
Murray BrownMicrosoft Cloud Azure/Excel Solution DeveloperAuthor Commented:
Thanks 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.