2016-09-21 50 views
-1

嗨,我有一個Windows窗體應用程序,需要根據提供的登錄證書打開不同的頁面。如果提供管理員證書(即用戶名=管理員),則稱爲「AdminPage」的窗體表單應用程序應該被調用爲Up。否則應該叫做「Main_Page」的窗體表單應用程序。如何根據登錄憑證設置特定的「登錄後選項」?

我的代碼給我提示「與此命令關聯的DataReader仍處於打開狀態,必須先關閉它」。

這是我的代碼;

try 
      { 
       SqlConnection cn = new SqlConnection("Data Source=PV10\\LOCALSERVER;Initial Catalog=SmallSoftwareDB;Integrated Security=True;Pooling=False"); 
       SqlCommand cmd = new SqlCommand("select * from UserCredentials where Username='" + textBox1.Text + "' and Password='" + textBox2.Text + "'", cn); 
       SqlDataReader dr; 
       cn.Open(); 
       dr = cmd.ExecuteReader(); 
       int cnt = 0; 
       while (dr.Read()) 
       { 
        cnt++; 
       } 
       if (cnt == 1) 
       { 
        MessageBox.Show("Successful Login...", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); 
        string query = "select Username, Password from UserCredentials where Username='Administrator"; 
        SqlCommand cmdA = new SqlCommand(query, cn); 
        dr = cmdA.ExecuteReader(); 
        int k = 0; 
        while(dr.Read()) 
        { 
         k++; 
        } 
        if(k == 1) 
        { 
         AdminPage A_P = new AdminPage(); 
         A_P.Tag = this; 
         A_P.Show(this); 
         Hide(); 
        } 
        Main_Page Mp = new Main_Page(); 
        Mp.Tag = this; 
        Mp.Show(this); 
        Hide(); 
        cn.Close(); 
        textBox1.Clear(); 
        textBox2.Clear(); 
       } 
       else 
       { 
        MessageBox.Show("Invalid UserName or Password", "Message", MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning); 
        textBox1.Clear(); 
        textBox2.Clear(); 
       } 
      } 
      catch (Exception err) 
      { 
       MessageBox.Show(err.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Warning); 
      } 
+3

你很容易被SQL注入,在文本框中放一個'''看看會發生什麼。改爲使用參數化查詢。 –

回答

0
try { 

的SqlConnection CON =新的SqlConnection( 「數據源= PV10 \的LocalServer;初始目錄= SmallSoftwareDB;集成安全性= TRUE;池=假」); con.Open();字符串Lg =「選擇用戶名,密碼從UserCredentials其中用戶名='」+ textBox1.Text +「'AND密碼='」+ textBox2.Text +「'」; SqlCommand cmd = new SqlCommand(Lg,con); SqlDataReader dr; dr = cmd.ExecuteReader(); int t = 0; while(dr.Read()){t ++; } if(t == 1){MessageBox.Show(「Successful Login」,「」,MessageBoxButtons.OK,MessageBoxIcon.Information); ){AdminPage Ap = new AdminPage(); Ap.Tag = this; Ap.Show(本); textBox1.Clear(); textBox2.Clear();隱藏(); }其他{Main_Page Mp = new Main_Page(); Mp.Tag = this; Mp.Show(本); textBox1.Clear(); textBox2.Clear();隱藏(); }} else {MessageBox.Show(「無效的用戶名或密碼」,「」,MessageBoxButtons.RetryCancel,MessageBoxIcon.Stop); textBox1.Clear(); textBox2.Clear(); }} catch(Exception ex){MessageBox.Show(ex.Message,「」,MessageBoxButtons.AbortRetryIgnore,MessageBoxIcon.Warning); }}