开发者

How to close executereader in asp.net?

I am using more then one repeater on same page. But when I use Execute reader for 2nd repeater then it gives exception that there is already execute reader running.. so close it. I put ExecuteReader(CommandBehavior.CloseConnection) b开发者_如何学Cut it give error that command behaviour doesn't exists... Any idea about this issue?


You need to explicitly close the DataReader if you specify that CommandBehavior, it will not do it for you.

http://msdn.microsoft.com/en-us/library/y6wy5a0f.aspx


Personally I would bind UI controls to strongly typed objects. So for example I would define a Product model:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
}

then a method to read products from the database:

public static IEnumerable<Product> GetProducts()
{
    using (var conn = new SqlConnection("Some connection string"))
    using (var cmd = conn.CreateCommand())
    {
        conn.Open();
        cmd.CommandText = "SELECT prod_id, prod_name FROM products";
        using (var reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                yield return new Product
                {
                    Id = reader.GetInt32(reader.GetOrdinal("prod_id")),
                    Name = reader.GetString(reader.GetOrdinal("prod_name")),
                };
            }
        }
    }
}

and in the web tier I would call this method to fetch my products and bind them to some UI controls:

protected void Page_Load(object sender, EventArgs e)
{
    var products = Db.GetProducts().ToArray();

    repeater1.DataSource = products;
    repeater2.DataSource = products;
    gridView.DataSource = products;
    ...
}

And when you get sick of writing those SQL queries you might take a look at an ORM, such as Entity Framework for example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜