2013-09-28 40 views
0

我創建了我的數據庫如下:我不得不從SQL Server檢索值2008數據庫

userid, password, type

現在在我的login.aspx.cs我想代碼,這樣如果userid和密碼匹配和用戶屬於U型,那麼它將去userpage,如果類型是A然後去管理頁面。代碼顯示在這裏,但如何將其發送到該類型。我很困惑如何檢索和比較,然後將其重定向到下一頁。

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 [email protected] and [email protected]"; 
     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>"); 
     } 
    } 
} 
+0

類型列將在'DataTable dt'中(應該是第一行也是唯一的一行); 'dt.Rows [0] [「type」]。ToString()'會給你的值。不過,我會推薦使用'SqlDataReader'來代替創建整個'DataTable'。 – Tim

回答

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

如果沒有行,第二行是否會引發錯誤? – Vulcronos

+0

@Vulcronos,絕對!很好地抓住我的朋友。 –

+0

@neoistheone ..我不明白你的代碼的第二行......它有三元運算符。 – user2334012

1

你後檢查:

if(dt.Rows.Count > 0) 

添加其他的檢查,看

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

如果爲true,進入管理頁面,否則到了用戶頁面。

+0

+1爲另一個可行的解決方案。 –

相關問題