当前位置: 代码迷 >> ASP.NET >> 已有打开的与此命令相关联的 DataReader,必须首先将它关闭。解决办法
  详细解决方案

已有打开的与此命令相关联的 DataReader,必须首先将它关闭。解决办法

热度:7772   发布时间:2013-02-25 00:00:00.0
已有打开的与此命令相关联的 DataReader,必须首先将它关闭。
C# code
这是我的代码,我在网上找了很久,也知道它错的原因,但我还是不能改好它。还希望帮我优化一下我的代码。谢谢...        string cnsql = "server=.;database=wuliu;Integrated Security=SSPI";        SqlConnection mycon = new SqlConnection(cnsql);        mycon.Open();        string str = "select * from dingdan where  ID = '" + Session ["danhao"] + "'";        SqlCommand cmd = new SqlCommand();        cmd.Connection = mycon;        cmd.CommandText = "select * from dingdan where  ID = '" + Session["danhao"] + "'";        SqlDataReader dr = cmd.ExecuteReader();        if (dr.Read())        {            SqlDataAdapter sda = new SqlDataAdapter(str, mycon);            DataSet ds = new DataSet();            sda.Fill(ds, "mytb");            DataView dv = ds.Tables["mytb"].DefaultView;            GridView1.DataSource = dv;            GridView1.DataBind();            dr.Close();        }        else {            Response.Write("<script language='javascript'> alert('查询不到你的订单号,请电我们公司电话核实') ;window.location.href = 'index.aspx';</script>");        }        mycon.Close();


------解决方案--------------------------------------------------------
if (dr.Read())
{
SqlDataAdapter sda = new SqlDataAdapter(str, mycon);
DataSet ds = new DataSet();
sda.Fill(ds, "mytb");
DataView dv = ds.Tables["mytb"].DefaultView;
GridView1.DataSource = dv;
GridView1.DataBind();
dr.Close();
}

你想做什么操作?dr.Read()你打开的是select * from dingdan where ID = '" + Session ["danhao"] + "'";

你又在Read()里面操作select * from dingdan where ID = '" + Session ["danhao"] + "'";这是不允许的


------解决方案--------------------------------------------------------
C# code
        string cnsql = "server=.;database=wuliu;Integrated Security=SSPI";        SqlConnection mycon = new SqlConnection(cnsql);        mycon.Open();        string str = "select * from dingdan where  ID = '" + Session ["danhao"] + "'";        SqlDataAdapter sda = new SqlDataAdapter(str, mycon);        DataSet ds = new DataSet();        sda.Fill(ds, "mytb");        if(ds.Tables["mytb"].Rows.Count>0)        {            DataView dv = ds.Tables["mytb"].DefaultView;            GridView1.DataSource = dv;            GridView1.DataBind();            dr.Close();        }                else {            Response.Write("<script language='javascript'> alert('查询不到你的订单号,请电我们公司电话核实') ;window.location.href = 'index.aspx';</script>");        }        mycon.Close();
  相关解决方案