public SqlDataReader Getgrxx(int userID)
        { ///获取连接字符串
            string connectionString = ConfigurationManager.ConnectionStrings["SQLCONNECTIONSTRING"].ConnectionString;
            ///创建连接
            SqlConnection con = new SqlConnection(connectionString);
            ///创建SQL语句
            string cmdText = "SELECT * FROM tg_gr WHERE grid=@UserID";
            ///创建SqlCommand
            SqlCommand cmd = new SqlCommand(cmdText, con);
            ///创建参数并赋值
            cmd.Parameters.Add("@UserID", SqlDbType.Int, 4);
            cmd.Parameters[0].Value = userID;
            ///定义SqlDataReader
            SqlDataReader dr;
            try
            {   ///打开连接
                con.Open();
                ///读取数据
                dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            }
            catch (Exception ex)
            {   ///抛出异常
                throw new Exception(ex.Message, ex);
            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                    con.Dispose();                }            }            return dr;
        }
我加入finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                    con.Dispose();                }            }
提示错误:阅读器关闭时 Read 的尝试无效。
如果我不加入最好关闭仅仅是 dr.Close();
        dr.Dispose();没有关闭con

解决方案 »

  1.   

    打错字了:如果我不加入最好关闭仅仅是 dr.Close(); 
            dr.Dispose(); 不是最好是最后
      

  2.   

    con.Close(); 
    con.Dispose(); 这不是关闭了的吗???
      

  3.   

    finally 去掉.cmd.ExecuteReader(CommandBehavior.CloseConnection); //这个reader用完会自动关闭连接的你只要把
    你调用Getgrxx方法返回的那个reader用完后关闭就行了如:SqlDataReader dr = Getgrxx(xx);dr用完后dr.close();
      

  4.   

    同意4楼,但是你也可以在方法中不关闭,再写一个关闭con的方法,再你调用完SqlDataReader这个方法后再用类名.关闭con的方法即可了