2 zxt9615 zxt9615 于 2013.12.06 17:26 提问

关于c#的dr.Close();放哪里好?
     cn.ConnectionString = "server = (local);password = 123;uid = sa;database = keshe";
    cn.Open();

    SqlCommand cmd_jiage = new SqlCommand("select 出租价格 from 房屋表", cn);
    SqlDataReader dr = cmd_jiage.ExecuteReader();
    while (dr.Read())
    {

        if (dr["出租价格"].ToString().Trim() == TextBox1.Text)
        {

            SqlCommand cmd = new SqlCommand("select * from 房屋表 where 出租价格 = @jiage", cn);
            cmd.Parameters.Add("@jiage", TextBox1.Text);
            GridView1.DataSource = cmd.ExecuteReader();
            GridView1.DataBind();

        }
        else
        {
            Label1.Text = "asd";
        }
        dr.Close();
    }
    cn.Close();

1个回答

u012908616
u012908616   2013.12.07 12:15
已采纳

使用

using (SqlDataReader dr = cmd_jiage.ExecuteReader()) {
    while(dr.Read()) {
        // do the readings.....
    }
} // will be automatically disposed here, no Close is needed
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!