C# Asp.net SQLdatareader,而循环不断被忽略

C# Asp.net SQLdatareader,而循环不断被忽略,c#,asp.net,sql,web-services,sqldatareader,C#,Asp.net,Sql,Web Services,Sqldatareader,出于某种奇怪的原因,我的while循环被完全忽略了。突破点表明,它至少正在接近它,但甚至没有试图进入它。我可能遗漏了一些简单化的东西 namespace website { public partial class Account : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Login_Click1(object se

出于某种奇怪的原因,我的while循环被完全忽略了。突破点表明,它至少正在接近它,但甚至没有试图进入它。我可能遗漏了一些简单化的东西

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

    }
    protected void Login_Click1(object sender, EventArgs e)
    {
        pullfrom();
    }



    private void pullfrom()
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = @"Data Source=WSERV2012CNTRLR\SQLEXPRESS,1433; Initial Catalog=Dackup; User ID=user; Password=password"; 
        string username = user.Text.ToString();
        string password = pass.Text.ToString(); //Clients username and password     
        try
        {
            con.Open();
        }

         catch
        {
            correct.Text = "Not able to connect. Please try again in 5 minutes".ToString();
            correct.Visible = true; 
        }

        SqlCommand command = new SqlCommand("Select * from dackupinfo where username=@username and password=@password;", con);
        command.Parameters.Add("@username", SqlDbType.VarChar).Value = username;
        command.Parameters.Add("@password", SqlDbType.VarChar).Value = password;
        SqlDataReader reader = command.ExecuteReader();
        while(reader.Read()) // Continues without going into the while loop.
        {

            // Console.WriteLine(reader["susername"].ToString());
            // Console.WriteLine(reader["spassword"].ToString()); //sftpserver/username
            string finder = reader["username"].ToString();
            if (finder == null)
            {
                correct.Text = "Incorrect Credentials".ToString(); // Need to look into; as I can't get it to work. 
                correct.Visible = true;

            }
            if (finder != null)
            {
                Response.Redirect("UserCenter.aspx");

            }
            reader.Close();
        }
        con.Close();


    }


}

}`

已修复。这是正确的代码

         SqlDataReader reader = command.ExecuteReader();
        if (reader.Read())
        {
            if (reader != null)
            {
                Response.Redirect("UserCenter.aspx");
            }
        }
            else
            {
                correct.Text = "Incorrect Credentials".ToString(); 
                correct.Visible = true;
            }

        reader.Close();
        con.Close();

这不是很简单吗。Read返回false,表示没有要读取的项。检查sql语句&并确保数据库中确实存在数据。这非常简单。只是没有考虑不被读取的空引用。OP通常不允许发布答案。是的,有一个条件,如果你被这个问题严重困扰,而我们中很少有人无法解决这个问题,你就会意识到这不是一件容易的事情,不管怎样,你解决了这个问题。。在这种情况下,为了帮助他人,您可以将您的解决方案作为答案发布。。