2014-10-09 32 views
-1

是新WPF中我工作的項目和正在錯誤的無效嘗試時,不存在數據讀取讀取 現在用的代碼 -Winform的無效嘗試當沒有數據存在

 SqlConnection l_oConn=null; 
     try 
     { 
      l_oConn = new SqlConnection("Data Source=ASHISH;Initial Catalog=iReg;Integrated Security=True"); 
      if (txt_userid.Text == "" || txt_password.Text == "") 
      { 
       MessageBox.Show("Please Enter the Id and Password", "Login Error"); 
       return; 
      } 
      else if (l_oConn.State == System.Data.ConnectionState.Closed) ; 
      { 
       l_oConn.Open(); 
      } 
      SqlCommand l_oCmd = new SqlCommand("SELECT * FROM EmpLogin", l_oConn); 
      SqlDataReader l_oDr = l_oCmd.ExecuteReader(); 
      int count = 0; 
      while (l_oDr.HasRows) 
      { 
       l_oDr.Read(); 
       string ID, Password; 
       ID = l_oDr.GetValue(0).ToString().Trim(); 
       Password = l_oDr.GetValue(1).ToString().Trim(); 
       if (ID == txt_userid.Text && Password == txt_password.Text) 
       { 
        count = count + 1; 
        StRegistration strpage = new StRegistration(); 
        this.NavigationService.Navigate(strpage); 
       } 
      } 

      l_oDr.Close(); 
      if (count == 0) 
      { 
       MessageBox.Show("Please enter the Valid id and password", "Login Error"); 

      } 

     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
     finally 
     { 
      if (l_oConn != null) 
      { 
       if (l_oConn.State == ConnectionState.Open) 
        l_oConn.Close(); 
       l_oConn.Dispose(); 
      } 
     } 
+1

WinForms或WPF?做出選擇並告訴我們。 – 2014-10-09 07:17:35

+0

在哪條線上?你調試了你的代碼嗎?你確定'SELECT * FROM EmpLogin'返回任何數據嗎? – 2014-10-09 07:20:02

回答

0

你需要至少讀取一次數據讀取器以從數據讀取器獲取行。因此,代碼從

while(l_oDr.HasRows) 
{ 
    // Your logic 
} 

while (l_oDr.Read()) 
{ 

} 
0

更改您的代碼從

 while (l_oDr.HasRows) 
     { 
      l_oDr.Read(); 
      string ID, Password; 
      ID = l_oDr.GetValue(0).ToString().Trim(); 
      Password = l_oDr.GetValue(1).ToString().Trim(); 
      if (ID == txt_userid.Text && Password == txt_password.Text) 
      { 
       count = count + 1; 
       StRegistration strpage = new StRegistration(); 
       this.NavigationService.Navigate(strpage); 
      } 
     } 

改變

 if (l_oDr.HasRows) 
     { 
      while(l_oDr.Read()) 
      { 
       string ID, Password; 
       ID = l_oDr.GetValue(0).ToString().Trim(); 
       Password = l_oDr.GetValue(1).ToString().Trim(); 
       if (ID == txt_userid.Text && Password == txt_password.Text) 
       { 
        count = count + 1; 
        StRegistration strpage = new StRegistration(); 
        this.NavigationService.Navigate(strpage); 
       } 
      } 
     } 

因爲首先你應該檢查行的存在與否在DataReader之後,你應該廁所p遍歷所有行。

相關問題