系统堆栈溢出异常无限循环

时间:2015-08-26 05:34:17

标签: c# asp.net sql-server

我收到System.Stack.Overflow.Exception的消息:

  

确保没有无限循环或无限递归。

但我不知道这段代码有什么问题。

    public string Projects()
    {
        using (SqlConnection con = new SqlConnection(str))
        {
            string htmlStr = "";
            SqlCommand cmd = new SqlCommand("Sp_oldprojects", con);
            cmd.Parameters.AddWithValue("@AgenId", Session["AgencyId"].ToString());
            cmd.CommandType = CommandType.StoredProcedure;
            con.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                int ProjId = reader.GetInt32(0);
                string ProjTitle = reader["ProjTitle"].ToString();

                htmlStr += "<tr><td>" + ProjId + "</td>" +  ProjTitle + "<td><a href=\"OldProjView.aspx?pId=" + ProjId + "\" class=\"btn btn-small\" title=\"Detailed View\"><i class=\"icon-search\"></i></td>" + "</tr>";
            }

            return htmlStr;
        }
    }

Image showing the problem

获取所有项目的程序

CREATE procedure sp_oldprojectsa 
@AgenId int
As 
Begin
Select * from OldProjects where AgencyId=@AgenId
End

在Call Stack中按摩:     [外部代码]     已超出Visual Studio支持的最大堆栈帧数。

1 个答案:

答案 0 :(得分:0)

你几乎就在那里,在你的while循环之后你只是缺少reader.Close();

 public string Projects()
{
    using (SqlConnection con = new SqlConnection(str))
    {
        string htmlStr = "";
        SqlCommand cmd = new SqlCommand("Sp_oldprojects", con);
        cmd.Parameters.AddWithValue("@AgenId", Session["AgencyId"].ToString());
        cmd.CommandType = CommandType.StoredProcedure;
        con.Open();
        SqlDataReader reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            int ProjId = reader.GetInt32(0);
            string ProjTitle = reader["ProjTitle"].ToString();

            htmlStr += "<tr><td>" + ProjId + "</td>" +  ProjTitle + "<td><a href=\"OldProjView.aspx?pId=" + ProjId + "\" class=\"btn btn-small\" title=\"Detailed View\"><i class=\"icon-search\"></i></td>" + "</tr>";
        }
        reader.Close();
        return htmlStr;
    }
}

查看将通过DataReader的this link