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

|
      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)。   SqlDataReader的默认位置在第一条记录之前。因此,您必须调用Read才能开始访问任何数据。     

要回复问题请先登录注册