Dynamic GridView AllowPaging returns error on DataBind
I've added a GridView to a PlaceHolder on my web page, and am setting it's datasource to a linq query. The trouble is that when control runs though gv.DataBind();
it'll blast on my face returning an Object not set bla bla bla error.
The stack trace looks like
at System.Web.UI.WebControls.GridView.get_StateFormatter() at System.Web.UI.WebControls.GridView.BuildCallbackArgument(Int32 pageIndex) at System.Web.UI.WebControls.GridView.CreateNumericPager(TableRow row, PagedDataSource pagedDataSource, Boolean addFirstLastPageButtons)开发者_如何学运维 at System.Web.UI.WebControls.GridView.InitializePager(GridViewRow row, Int32 columnSpan, PagedDataSource pagedDataSource) ....
and my code is
var query = from list in dc.mytable
select list;
gv.DataSource = query.ToList();
gv.DataBind();
After looking around for solutions for quite a while, I came up with a suggestion which worked, and I am sharing with you, should you need. Unfortunately I closed the browser and don't remember where I saw it, to give the credit to the guy who solved my problem.
I'm posting it here because I didn't find any answer here that solved my problem.
The reason for this problem was that since the GridView is being added dynamically, there is some issue with the StateFormatter not being set yet (or something like that), so all it takes to resolve this is adding an event handler for the Load event and moving the gv.DataBind(); there:
gv.DataSource = query;
gv.Load += (s, e) => {
gv.DataBind();
}
Works like a charm :)
精彩评论