简体   繁体   English

如何在C#ASP.NET中获取数据表行的值

[英]How to get value of DataTable Row in C# asp.net

i am learning asp.net with c# by myself, and i have a problem with DataRows, in db i have users table and there is isadmin column which value is int , i want to redirect users to different page and admins to admin page, but the problem is all users redirects to admin page. 我正在用c#自己学习asp.net ,我在使用DataRows时遇到了问题,在数据库中我有users表,并且有isadmin列,其值是int ,我想将用户重定向到其他页面,并将admins重定向到admin页面,但是问题是所有用户都重定向到管理页面。

Here is my code; 这是我的代码;

 protected void btnLogin_Click(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection(conString);
        conn.Open();
            SqlCommand cmd = new SqlCommand("SELECT username, pass FROM users 
                                where username = '"+txtUser.Text+"'
                                and pass='"+txtPass.Text+"'"
                                , conn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);

        SqlCommand cmd1 = new SqlCommand("Select username, isadmin From users", conn);
        SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
        DataTable dt1 = new DataTable();
        da1.Fill(dt1);

        conn.Close();
        if (dt.Rows.Count > 0)
        {
            Session["id"] = txtUser.Text;
            if (dt1.Rows[0]["isadmin"].ToString() == "1")
            {
                Response.Redirect("~/admin.aspx");
            }
            else
            {
                Response.Redirect("~/default.aspx");
            }


            //Response.Redirect("~/default.aspx");

            Session.RemoveAll();
        }
        else
        {
            lblMsg.ForeColor = System.Drawing.Color.Red;
            //lblMsg.Text= msg ;

                /*Response.Write("<script>
                alert('Please enter valid Username and Password')
                </script>"); */
        }

Can you please tell me what is wrong? 你能告诉我出什么问题了吗?

Use the first query with dt as it's based on a single user. 将第一个查询与dt一起使用,因为它是基于单个用户的。 The problem is dt1 gets all users and the first record in that datatable is an admin 问题是dt1获取所有用户,并且该数据表中的第一条记录是管理员

if (dt.Rows[0]["isadmin"].ToString() == "1") {

Remove the second query with dt1 and make sure you add isadmin to the first SQL query. 使用dt1删除第二个查询,并确保将isadmin添加到第一个SQL查询中。

SqlCommand cmd = new SqlCommand("SELECT username, pass, isadmin FROM users where username = @UserName and pass= @Pass", conn); 

See how I use parameterized username and password, that is to protect against SQL injection, definitely read up on that!!! 看看我如何使用参数化的用户名和密码,这是为了防止SQL注入,请务必仔细阅读!!!

There are several things wrong with your code: 您的代码有几处错误:

  1. All users are redirected to the admin page since you are checking the isAdmin in the wrong query. 由于您在错误的查询中检查isAdmin ,因此所有用户都将重定向到admin页面。 Your second query has no where clause which means it will return all the users in the table. 您的第二个查询没有where子句,这意味着它将返回表中的所有用户。 The first user it returns has the isAdmin value of 1 . 它返回的第一个用户的isAdmin值为1
    You don't actually need two queries, just one. 您实际上不需要两个查询,只需一个。

  2. You must use parameterized queries, otherwise you are leaving an open door to SQL injection attacks. 您必须使用参数化查询,否则您将对SQL注入攻击敞开大门。

  3. wrap all IDisposable instances in a using statement. 将所有IDisposable实例包装在using语句中。

Your code should look more like this: 您的代码应如下所示:

protected void btnLogin_Click(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    using(SqlConnection conn = new SqlConnection(conString))
    {
        using(SqlCommand cmd = new SqlCommand("SELECT username, pass, isadmin FROM users where username = @UserName and pass=@Pass", conn))
        {
            cmd.Parameters.Add("@UserName", SqlDbType.VarChar).Value = txtUser.Text;
            cmd.Parameters.Add("@Pass", SqlDbType.VarChar).Value = txtPass.Text;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
        }   

    }
    if (dt.Rows.Count > 0)
    {
        Session["id"] = txtUser.Text;
        if (dt1.Rows[0]["isadmin"].ToString() == "1")
        {
            Response.Redirect("~/admin.aspx");
        }
        else
        {
            Response.Redirect("~/default.aspx");
        }


        //Response.Redirect("~/default.aspx");

        Session.RemoveAll();
    }
    else
    {
        lblMsg.ForeColor = System.Drawing.Color.Red;
        //lblMsg.Text= msg ;

        //Response.Write("<script>alert('Please enter valid Username and Password')</script>");
    }

}

Please Try this 请尝试这个

protected void btnLogin_Click(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection(conString);
    conn.Open();
    SqlCommand cmd =
        new SqlCommand(
            "SELECT username, pass, isadmin FROM users where username = '" + txtUser.Text + "' and pass='" + txtPass.Text +
            "'", conn);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);

    conn.Close();
    if (dt.Rows.Count > 0)
    {
        Session["id"] = txtUser.Text;
        if (dt.Rows[0]["isadmin"].ToString() == "1")
        {
            Response.Redirect("~/admin.aspx");
        }
        else
        {
            Response.Redirect("~/default.aspx");
        }


        //Response.Redirect("~/default.aspx");

        Session.RemoveAll();
    }
    else
    {
        lblMsg.ForeColor = System.Drawing.Color.Red;
        //lblMsg.Text= msg ;

        //Response.Write("<script>alert('Please enter valid Username and Password')</script>");
    }
}

In your first query you need to get isadmin also and on the base of that result you can check either it is 1 or not and can redirect to what ever page you like. 在第一个查询中,您还需要获取isadmin并且根据该结果可以检查它是否为1并可以重定向到您喜欢的任何页面。 So it will be as follow: 因此,将如下所示:

protected void btnLogin_Click(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection(conString);
    conn.Open();
    SqlCommand cmd = new SqlCommand("SELECT username, pass, isadmin FROM users where username = '"+txtUser.Text+"' and pass='"+txtPass.Text+"'", conn);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    conn.Close();
    if (dt.Rows.Count > 0)
    {
        Session["id"] = txtUser.Text;
        if (dt.Rows[0]["isadmin"].ToString() == "1")
        {
            Response.Redirect("~/admin.aspx");
        }
        else
        {
            Response.Redirect("~/default.aspx");
        }
        //Response.Redirect("~/default.aspx");
        Session.RemoveAll();
    }
    else
    {
        lblMsg.ForeColor = System.Drawing.Color.Red;
        //lblMsg.Text= msg ;
        //Response.Write("<script>alert('Please enter valid Username and Password')</script>");
    }
}

Your second query lacks the filter on a user name: 您的第二个查询缺少用户名过滤器:

Select username, isadmin From users

So whatever it fetches - if the first row contains 1 as IsAdmin, all users will be redirected to the admin page. 因此,无论获取什么内容-如果第一行包含1作为IsAdmin,则所有用户都将被重定向到管理页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM