4
      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);
                }

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

可能是如果循环运行太多次..那么抛出异常对吗?

4

1 回答 1

4

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

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

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

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

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

于 2011-06-25T14:23:26.357 回答