加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – InvalidOperationException:没有数据时读取的尝试无

发布时间:2020-12-16 10:00:36 所属栏目:asp.Net 来源:网络整理
导读:SqlConnection conn = new SqlConnection(AllQuestionsPresented.connectionString); SqlCommand cmd = new SqlCommand(sb.ToString(),conn); cmd.Parameters.Add("@ThreadsID",SqlDbType.Int).Value = commentIDe; cmd.Parameters.Add("@CommentsID",SqlDbT
SqlConnection conn = new SqlConnection(AllQuestionsPresented.connectionString);

    SqlCommand cmd = new SqlCommand(sb.ToString(),conn);
    cmd.Parameters.Add("@ThreadsID",SqlDbType.Int).Value = commentIDe;
    cmd.Parameters.Add("@CommentsID",SqlDbType.Int).Value = commentIDe;
    try
    {
        conn.Open();
        SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

        if (dr != null && dr["Comments"] != null && dr["Name"] != null && dr["Date"] != null && dr["UserID"]!=null)//> Invalid attempt to read when no data is present.
        {
            Comment = dr["Comments"].ToString();
            UserName = dr["Name"].ToString();
            Reputation=Int32.Parse(dr["Reputation"].ToString());
            Time = (DateTime)AllQuestionsPresented.TryParse(dr["Date"].ToString());
            UserID = (Guid)dr["UserID"];
        }
        dr.Close();
    }
    finally
    {
        if (conn.State != ConnectionState.Closed)
        {
            conn.Close();
        }
    }

注意:我用while(dr.Read){}来迭代那段代码……这里没有显示.

为什么我会得到那个例外,我该如何摆脱它

更新:

while (reader.Read())//Command runs through all the ThreadIDs that i have!
                {
                    Comments allQ = new Comments((int)reader["CommentsID"]);
                    allComments.Add(allQ);
                }

注释是代码所在的类,它在构造函数中有一个运行我提供的代码的方法.

可能是因为循环运行的次数太多了..然后异常被抛出我是对的吗?

解决方法

您的代码的以下部分是非法的

SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

if (dr != null && dr["Comments"] ...)

在访问SqlDataReader的索引器之前,您必须调用一次Read方法(并验证它是否返回true),如文档所述:

The default position of the SqlDataReader is before the first record. Therefore,you must call Read to begin accessing any data.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读