Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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.
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();
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.