在登录页面中:
Session("FirstName") = txtUserName.Text
Response.Redirect("CusRecords.aspx")
在第二页:
lbl1.Text = Session("FirstName").ToString
我使用了该代码,但出现此错误:
Object reference not set to an instance of an object.
that error refers to lbl1.Text = Session("FirstName").ToString
这是登录页面的完整代码:
Public Class _Default
Inherits System.Web.UI.Page
Public s As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Session.Clear()
Session.Abandon()
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim con As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("RegconnectionString").ConnectionString)
con.Open()
Dim userCount As Int32 = GetUserCount(txtUserName.Text)
Dim paasCount As Int32 = GetPassCount(TxtPassword.Text)
If userCount > 0 And paasCount > 0 Then
Session("FirstName") = txtUserName.Text
Else
lblErr.Visible = True
End If
Response.Redirect("CusRecords.aspx")
End Sub
' Method to check existence
Public Shared Function GetUserCount(ByVal userName As String) As Int32
Const sql = "SELECT COUNT(*) FROM Registration where username = @UserName"
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("RegconnectionString").ConnectionString)
Using cmd = New SqlCommand(sql, con)
cmd.Parameters.AddWithValue("@UserName", userName)
con.Open()
Using reader = cmd.ExecuteReader()
If reader.HasRows Then
reader.Read()
Dim count As Int32 = reader.GetInt32(0)
Return count
End If
End Using
End Using
End Using
End Function
Public Shared Function GetPassCount(ByVal password As String) As Int32
Const sql = "SELECT COUNT(*) FROM Registration where password = @Password"
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("RegconnectionString").ConnectionString)
Using cmd = New SqlCommand(sql, con)
cmd.Parameters.AddWithValue("@Password", password)
con.Open()
Using reader = cmd.ExecuteReader()
If reader.HasRows Then
reader.Read()
Dim count As Int32 = reader.GetInt32(0)
Return count
End If
End Using
End Using
End Using
End Function
Protected Sub txtUserName_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles txtUserName.TextChanged
End Sub
End Class
其他页面:
Public Class CusRecords
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Session("FirstName") IsNot Nothing Then
lbl1.Text = DirectCast(Session("FirstName"), String)
Else
lbl1.Text = "It is empty"
End If
End Sub
结束类