Winform在没有数据的情况下进行无效的读取尝试
本文关键字:无效 读取 情况下 数据 Winform | 更新日期: 2023-09-27 18:25:58
我是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();
}
}
您需要至少读取一次数据读取器才能从数据读取器中获取行。所以更改的代码
while(l_oDr.HasRows)
{
// Your logic
}
至
while (l_oDr.Read())
{
}
从更改代码
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中是否存在行,然后您应该遍历所有行。