I have a grid displaying a collection. When you click on one of the items in the grid, you can edit the item and store it back in the grid.
I line up all of these changes and store them all back to the data store in one shot when the submit button is pressed. To do this, I persist the collection across postbacks using an entity spaces proxy class and serializing them into the viewstate.
In effect, my code works like this. The first time the page is loaded, I load the collection and store it in a variable (this is the variable that gets persisted as described above) and this is the source for e.collection of my EsDataSource. On postbacks, I retrieve the collection from the viewstate rather than loading it again from the data store. This means that the collection EsDataSource is the one with the user's changes.
All this works fine, but only when I have AutoSorting="false". If I set it to "true", my collection seems to revert back to its old values (before changes were made) on each and every post back.
When AutoSorting="true" are you storing the collection in the viewstate too? Does this in some way wind up overwriting my changes? Is there some way to prevent that?
Code:
protected override object SaveControlState()
{
//Persist data across postbacks
object[] state = new object[1];
if (_itemHistory != null)
{
ItemHistoryCollectionProxyStub itemHistoryProxy = new ItemHistoryCollectionProxyStub(_itemHistory);
XmlSerializer itemSerializer = new XmlSerializer(itemHistoryProxy.GetType());
StringWriter itemSW = new StringWriter();
itemSerializer.Serialize(itemSW, itemHistoryProxy);
state[0] = itemSW.ToString();
}
return state;
}
protected override void LoadControlState(object savedState)
{
//Retrieve data across postbacks
object[] state = (object[])savedState;
if (state[0] != null)
{
XmlSerializer itemSerializer = new XmlSerializer(typeof(ItemHistoryCollectionProxyStub));
StringReader itemSR = new StringReader(state[0].ToString());
ItemHistoryCollectionProxyStub itemHistoryProxy = (ItemHistoryCollectionProxyStub)itemSerializer.Deserialize(itemSR);
_itemHistory = itemHistoryProxy.GetCollection(); //Convert it back to the collection.
}
}
protected void EsDataSource_ItemHistory_esSelect(object sender, esDataSourceSelectEventArgs e)
{
if (_itemHistory != null)
{
e.Collection = _itemHistory;
}
else
{
_itemHistory = new ItemHistoryCollection().LoadAll();
}
}