Integer values are being reset to 0 when the sub in which they are assigned values is ended
In the following code I have two class scoped variables intCompanyID
and intEmployeeID
. When I set them to a value in btnFetch_Click
then try to read them later in btnSubmit_Click
they are set to zero.
Why is this?
Option Explicit On
Imports MySql.Data.MySqlClient
Imports System.Data
Public Class EmployeeQuestionaire
Inherits System.Web.UI.Page
Dim intCompanyID A开发者_StackOverflows Integer
Dim intEmployeeID As Integer
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
End Sub
Protected Sub btnFetch_Click(ByVal sender As Object, ByVal e As EventArgs)
Handles btnFetch.Click
intEmployeeID = Convert.ToInt32(txtUserID.Text)
intCompanyID = 1
msgbox (intEmpoyeeID & " " & intCompanyID) ' this shows the values
End Sub
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs)
Handles btnSubmit.Click
MsgBox(intCompanyID & " " & intEmployeeID) 'shows O O
End Sub
ASP.NET will not store any state in between trips to the web-server. Therefore, you will need to find somewhere to store your values. You can use the Session
object:
Protected Sub btnFetch_Click
Session ("MyEmployeeId") = Convert.ToInt32(txtUserID.Text)
End Sub
Protected Sub btnSubmit_Click
intEmployeeID = Session("MyEmployeeId")
End Sub
Alternatively, you can re-read the txtUserId
each time:
Protected Sub btnFetch_Click
intEmployeeid = Convert.ToInt32(txtUserID.Text)
End Sub
Protected Sub btnSubmit_Click
intEmployeeID = Convert.ToInt32(txtUserID.Text)
End Sub
There are many other ways, but ultimately I think you need a much better basic understanding of ASP.NET. It's very different to WinForms programming, or whatever you've used. For one, you really shouldn't use MsgBox
as your code will generally be running on a web-server with no-one to click "OK"!
Every time a page is posted back, the ASP.NET create the page object and generates all the controls and variables you have defined so you need to use ASP.NET state management technique to preserve the state between requests.
For instance,
Protected Sub btnFetch_Click(ByVal sender As Object, ByVal e As EventArgs)
Handles btnFetch.Click
int intEmployeeID;
int.TryParse(txtUserID.Text,out intEmployeeID);
Session("intCompanyID")=1
Session("intEmployeeID")=intEmployeeID;
msgbox (intEmpoyeeID & " " & Session("intCompanyID"))
End Sub
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs)
Handles btnSubmit.Click
If Not IsNothing(Session("intCompanyID")) Then
MsgBox(Session("intCompanyID) & " " & Session("intEmployeeID"))
End If
End Sub
精彩评论