阅读尝试无效时,没有数据是ASP.NET present [英] Invalid attempt to read when no data is present in ASP.NET

查看:159
本文介绍了阅读尝试无效时,没有数据是ASP.NET present的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用C#来学习ASP.NET,我试着写验证code作为

I am using C# to learn ASP.NET, I tried to write authentication code as

SqlCommand command = new SqlCommand("Select [ID] from [Inspector] WHERE [ID] ='111' AND [Password] ='111';", conn);

SqlDataReader dr = command.ExecuteReader();

if (dr[0].ToString() == username)
{
Session["UserAuthentication"] = username;
Session.Timeout = 1;
Response.Redirect("About.aspx");
}
else{
// ...
}

ID 是SQL Server类型数字的。

The ID is of type numeric in SQL Server.

问题是我总是得到异常:

The issue is I always get exception:

无效的尝试。

在此部分:如果(DR [0]的ToString()==用户名)

我试图直接执行的确切的SQL语句,我可以得到结果。

I tried to execute the exact SQL statement directly and I can get the result.

推荐答案

您需要遍历读者的行回来了 - 使用code是这样的:

You need to iterate over the reader's rows returned - using code something like this:

SqlDataReader dr = command.ExecuteReader();

if(dr.Read())
{
    if (dr[0].ToString() == username)
    {
        Session["UserAuthentication"] = username;
        Session.Timeout = 1;
        Response.Redirect("About.aspx");
    }
    else {
       // ...
    }
}

您需要调用 .Read() SqlDataReader的至少一次真正的阅读数据。

You need to call .Read() on the SqlDataReader at least once to actually read the data.

如果您打算读的行数有,你应该使用

If you plan to read as many rows as there are, you should use

while (dr.Read())
{
     .....
}

和处理返回的多行。

这篇关于阅读尝试无效时,没有数据是ASP.NET present的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆