Asp.net InvalidOperationException:当不存在数据时,读取尝试无效。(SQL)

Asp.net InvalidOperationException:当不存在数据时,读取尝试无效。(SQL),asp.net,sql,invalidoperationexception,Asp.net,Sql,Invalidoperationexception,注意:我确实使用while(dr.Read){}迭代了这段代码。。。这里没有显示 为什么我会得到这个例外,我如何摆脱它 更新: SqlConnection conn = new SqlConnection(AllQuestionsPresented.connectionString); SqlCommand cmd = new SqlCommand(sb.ToString(), conn); cmd.Parameters.Add("@ThreadsID", SqlD

注意:我确实使用while(dr.Read){}迭代了这段代码。。。这里没有显示

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

更新:

      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();
        }
    }
Comments是代码所在的类,它在构造函数中有一个方法,运行我介绍的代码


这可能是因为如果循环运行太多次。。然后抛出异常,对吗?

代码的以下部分是非法的

                 while (reader.Read())//Command runs through all the ThreadIDs that i have!
                {
                    Comments allQ = new Comments((int)reader["CommentsID"]);
                    allComments.Add(allQ);
                }
在访问SqlDataReader的索引器之前,必须调用Read方法一次(并验证其返回true),如文档所述:

SqlDataReader的默认位置在第一条记录之前。因此,您必须调用Read来开始访问任何数据


您在阅读器上的迭代方式似乎与此错误非常相关。你可以发布一个完整的代码片段吗?我可以使用这个:if(dr.HasRows){
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

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