我想单击按钮后查询数据库中有无TextBox1.Text所指用户,如有则生成Cookie,通过判断cookie有无改变页面。但我输入数据库中已有用户后,第一次单击按钮页面无变化,第二次才发生变化,为何?
   Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If Not Request.Cookies("EmailRegister") Is Nothing Then
            TextBox1.Visible = False
            Button1.Visible = False
            Label2.Visible = True
            Label2.Text = "You have successfully registered for Email updates"
        End If
    End Sub    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim lgConnection As New OleDbConnection("Provider=Microsoft.Jet.oledb.4.0;data source=C:\Inetpub\wwwroot\lg.mdb")
        Dim Selecting As New OleDbCommand("select count (username) from accounts where username=@User", lgConnection)
        Dim Param As New OleDbParameter("@User", OleDbType.VarChar, 20)
        Param.Value = TextBox1.Text
        Selecting.Parameters.Add(Param)
        Dim Result As Integer
        lgConnection.Open()
        Result = Selecting.ExecuteScalar
        lgConnection.Close()
        
     If result>0 then
        Dim Cookie As New HttpCookie("EmailRegister")
        Cookie.Value = TextBox1.Text
        Cookie.Expires = Now.AddSeconds(10)
        Response.Cookies.Add(Cookie)
     End If
    End Sub

解决方案 »

  1.   

    当然会有这样的结果了..你的按钮在点击后去判断数据库..然后存在的时候才赋予Cookie值..判断后并没有赋予相应的处理,所以第一点击的时候会赋予Cookie值..第二次点击的时候你的判断Cookie才会在Page_Load中起作用.
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim lgConnection As New OleDbConnection("Provider=Microsoft.Jet.oledb.4.0;data source=C:\Inetpub\wwwroot\lg.mdb")
            Dim Selecting As New OleDbCommand("select count (username) from accounts where username=@User", lgConnection)
            Dim Param As New OleDbParameter("@User", OleDbType.VarChar, 20)
            Param.Value = TextBox1.Text
            Selecting.Parameters.Add(Param)
            Dim Result As Integer
            lgConnection.Open()
            Result = Selecting.ExecuteScalar
            lgConnection.Close()
            
         If result>0 then
            Dim Cookie As New HttpCookie("EmailRegister")
            Cookie.Value = TextBox1.Text
            Cookie.Expires = Now.AddSeconds(10)
            Response.Cookies.Add(Cookie)
            TextBox1.Visible = False
            Button1.Visible = False
            Label2.Visible = True
            Label2.Text = "You have successfully registered for Email updates"     End If
        End Sub
      

  2.   

    页面事件触发的过程是: 先Page_Load,再Button1_Click. 所以第一次按钮点击,Page_Load中未找到Cookie,第二次点击才找到Cookie.
      

  3.   

    上面的几位都说明原因了
    最好你能在buttonclick里面判断后就得有相应的动作