我是wpf的新手正在处理项目,并且在没有数据时会收到无效尝试读取的错误 我正在使用代码 -
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();
}
}
答案 0 :(得分:0)
您需要至少读取一次datareader以从datareader获取行。所以从
更改代码while(l_oDr.HasRows)
{
// Your logic
}
到
while (l_oDr.Read())
{
}
答案 1 :(得分: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中是否存在行,然后你应该循环遍历所有行。