当为其分配值的子项结束时,整数值将重置为0

时间:2011-09-22 12:03:05

标签: asp.net mysql vb.net

在下面的代码中,我有两个类范围的变量intCompanyIDintEmployeeID。当我将它们设置为btnFetch_Click中的值时,请稍后在btnSubmit_Click中尝试将它们设置为零。

为什么会这样?

Option Explicit On
Imports MySql.Data.MySqlClient
Imports System.Data

Public Class EmployeeQuestionaire
Inherits System.Web.UI.Page

Dim intCompanyID As 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

2 个答案:

答案 0 :(得分:2)

ASP.NET不会在访问Web服务器之间存储任何状态。因此,您需要找到存储值的地方。您可以使用Session对象:

Protected Sub btnFetch_Click
    Session ("MyEmployeeId") = Convert.ToInt32(txtUserID.Text)
End Sub

Protected Sub btnSubmit_Click
    intEmployeeID = Session("MyEmployeeId")
End Sub

或者,您可以每次重新阅读txtUserId

Protected Sub btnFetch_Click
    intEmployeeid = Convert.ToInt32(txtUserID.Text)
End Sub

Protected Sub btnSubmit_Click
    intEmployeeID = Convert.ToInt32(txtUserID.Text)
End Sub

还有很多其他方法,但最终我认为您需要对ASP.NET有更好的基本了解。它与WinForms编程或您使用的任何内容都有很大的不同。首先,你真的不应该使用MsgBox,因为你的代码通常会在没有人点击“确定”的网络服务器上运行!

答案 1 :(得分:0)

每次回发页面时,ASP.NET都会创建页面对象并生成您定义的所有控件和变量,因此您需要使用ASP.NET state management技术来保留请求之间的状态。

例如,

  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