0

i have created my database as follows :

userid, password, type

Now in my login.aspx.cs I want to code such that if userid and password are matching and a user belongs to the type U then it will go to userpage and if type is A then go to admin page. The code is shown here but how to send it to the type. I am having confusion of how to retrieve and compare and then redirect it to the following page.

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

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string username = TextBox1.Text;
        string pass = TextBox2.Text;
        string  utp;
        string  connectionString = WebConfigurationManager.ConnectionStrings["newdb"].ConnectionString;
        SqlConnection con = new SqlConnection(connectionString);
        con.Open();
        string qry = "select * from login where uid=@username and pass=@pass";
        SqlCommand cmd = new SqlCommand(qry,con);
        cmd.Parameters.AddWithValue("@username",username);
        cmd.Parameters.AddWithValue("@pass",pass);

        SqlDataAdapter ad = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        ad.Fill(dt);
        if (dt.Rows.Count > 0)
            Response.Redirect("http://localhost:55575/WebSite13/admin/Adminpage.aspx");
        else
        {
            ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>");
        }
    }
}
4

2 回答 2

1

您快到了。你只需要做这个:

if (dt.Rows.Count > 0)
    Response.Redirect("http://localhost:55575/WebSite13/admin/Adminpage.aspx");

该代码表示​​,如果数据库中有任何行与我的查询匹配,即具有指定用户名和密码的用户,则重定向。然而,这并不是你真正想要做的,不是吗?你想检查那个类型。所以让我们稍微修改一下:

bool hasRows = dt.Rows.Count > 0;
string type = hasRows ? string.Empty : dt.Rows[0].Field<string>("type");

if (hasRows && type == "A")
    Response.Redirect("http://localhost:55575/WebSite13/admin/Adminpage.aspx");
else if (hasRows && type == "U")
    Response.Redirect("http://localhost:55575/WebSite13/admin/userpage.aspx");
于 2013-09-28T19:42:39.583 回答
1

检查后:

if(dt.Rows.Count > 0) 

添加另一个检查以查看

if(dt.Rows[0]["type"].ToString().Equals("A"))

如果为 true,则转到管理页面,否则转到用户页面。

于 2013-09-28T19:44:58.503 回答