C# – DataBind() in C#

asp.netcgridviewlinq-to-entities

I am fairly new to Entity framework as well as LINQ. I have used DataGridView before and to set the datasource to it

DataGridView1.datasource=dt; // dt=datatable

was enough. But while reading ASP.Net book they have given the code using Entity Framework as

using (PlanetWroxEntities myEntities = new PlanetWroxEntities())
{
    var allGenres = from genre in myEntities.Genres
    orderby genre.Name
    select new { genre.Name, genre.Reviews };
    GridView1.DataSource = allGenres;
    GridView1.DataBind();
}

Why is this DataBind()is used in the end. I have seen the MSDN document forDataBind()which says "(It) Binds a data source to the invoked server control and all its child controls."

And if I remove it, I get an error as "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection."

So I was just confused that what is thisDataBind()actually does? I have seen some people using DataBind for DataGridView also, and I am not sure why?

Thanks.

Best Answer

The DataBind method forces the datasource to be read and bound to the control. Since you databind within the PlanetWroxEntities context which you dispose afterwards, the control should read the data from the datasource before the PlanetWroxEntities disposes. In other words: before the database connection is closed.

A alternative is to force the query by calling the .ToList() method. This sets the DataSource property to a non-lazy list containing the concrete data.

using (PlanetWroxEntities myEntities = new PlanetWroxEntities())
{
    var allGenres = from genre in myEntities.Genres
    orderby genre.Name
    select new { genre.Name, genre.Reviews };
    GridView1.DataSource = allGenres.ToList();
}