简体   繁体   中英

I have to retrieve a value from sql server 2008 database

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>");
        }
    }
}

You're almost there. You just need to work this this a bit:

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

That code says that if there are any rows in the database that matched my query, which was a user with the specified user name and password, then redirect. However, that's not really what you want to do is it? You'd like to check that type. So let's modify that a bit:

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");

After you check:

if(dt.Rows.Count > 0) 

add another check to see

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

If true, go to the admin page, else go to the user page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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