Web DataGrid problem

  • Thread starter Thread starter Pete Davis
  • Start date Start date
P

Pete Davis

I'm using a web form DataGrid. When I populate the grid, I set the
DataSource to a collection and then call DataGrid.DataBind(). When looking
at the DataGrid in the debugger, the DataSource is set properly. When I then
get to the SelectedIndexChanged() event, the DataSource is set to null. I
have both the page and the datagrid set with enableViewState set to true.
The Items collection is valid and the Cells contain the proper data. What am
I missing? What happened to the DataSource?

Pete
 
When you use the DataGrid, the DataSource property is not kept in the
viewstate.
The approach to work with the datagrid is to re-fetch the datasource
everytime it changes.
In yout case, if you have information on each colelction item that you'd
want to use in the event handler, then put this information somewhere in the
row, like in a hidden input tag.
 
Do you know what the reasoning behind that is? I mean, it can't be to save
memory because the grid could just as easily hold onto the DataSource to
redraw itself as the item and cell collections. It would be really nice if
this were an optional "feature" because as it is, it means I need to store
the collection in the session.

Pete
 
This is meant to save viewstate usage. Serializing a collection in the
viewstate can produce huge HTML source. The datagrid just keeps what is
needed to redraw each cell. Whatever information you didn't use in the grid,
is lost.


--
TJoker, MCSD.NET
MVP: Paint, Notepad, Solitaire

****************************************
 
Hi Pete,

That's the expected behavior, to understand what is happening I think is
better explain a little how the state feature works, when you set the
enableViewState basically what you are saying is that the control is going
to be serialized inside a hidden control in the html page using a StateBag
object, if you view the source of the html page you will see this info.
Now the thing is that the DataSource has a reference to another object, if
it's serialized then the referenced object would also need to be serialized
this would create a HUGE overload to the page !!!
What was the solution?
It's your responsability to keep a reference to the datasource if you need
it, you can use several ways to do so, the easiest I think is using the
Session collection and reassign it in the OnLoad event of the page:

page_Load( object sender, System.EventArgs e)
{
if ( !IsPostBack)
{
grid.DataSource = collection;
Session["SavedCollection"] = collection;

}
else
grid.DataSource = ( CollectionType)Session["SavedCollection"];

}


Hope this help,
 
Back
Top