SQL Server:第一次加载页面时连接失败

时间:2014-05-26 13:08:20

标签: c# asp.net sql-server

我的网络应用程序中存在以下问题。

string strcon = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;

public string getLastLogin(string userName)
{
            SqlConnection conn = new SqlConnection(strcon);
            conn.Open();
            string q = "select lastAccess=convert(varchar, lastAccess, 100) from EBPRegistration where userName = '" + userName + "'";
            //string q = "select lastAccess from EBPRegistration where userName = '" + userName + "'";
            SqlCommand cmd = new SqlCommand(q, conn);
            SqlDataReader dr = cmd.ExecuteReader();

            string result = "";
            try
            {
                while (dr.Read())
                {
                    result = (dr["lastAccess"].ToString());
                }

            }
            catch (Exception)
            {
            }
            dr.Close();
            conn.Close();
            return result;
}

Page_Load方法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace EBPApps.backend
{
    public partial class LastLogin : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            DataController DbConnection = new DataController();
            string userName = Request.Form["userName"];

            string result = DbConnection.getLastLogin(userName);


            Response.Write(result);

        }
    }
}

每当我在页面加载时调用getLastLogin方法时,它会给出空结果。如果我再加载意味着,它给出了良好的结果。我认为这是第一次SqlConnection问题。但我不确定这一点。

帮帮我...... 提前谢谢......

1 个答案:

答案 0 :(得分:0)

如何在

中的Page_Load方法中包装代码
if(!IsPostBack)
{
  //your code here...
}