How to load, save and display data from GridView to XML? Not XML file on the hard disk, but a temporary XML variable to save it all in a single field of XML type in a database.
The gridview per se doesn't have any data - so you can't save any to disk.
Your gridview will be bound to a data source - a list of objects, a DataTable, anything - that's the data, and that can be saved to (and loaded from) disk.
Your easiest choice is to XML serialize the data to disk - or load it from there. You need to check into XML serialization.
Or check out the DataTable's ReadXml and WriteXml methods - they allow you to save a DataTable onto disk in XML format - or load it from a XML file on disk.
It can be as simple as this:
DataTable myData = new DataTable();
myData.ReadXml(@"C:\temp\mydatafile.xml");
// do some processing
myData.WriteXml(@"C:\temp\mydatafile.xml", XmlWriteMode.WriteSchema);
UPDATE:
if you want to store the XML into a string so you can dump it into a database, use this:
// write DataTable to memory stream as XML
MemoryStream memStm = new MemoryStream();
myData.WriteXml(memStm);
// read memory stream into a string variable
memStm.Position = 0;
string xmlContents = new StreamReader(memStm).ReadToEnd();
and then store your xmlContents
to the database.
Marc
Why do you want to store the historical data in the database? Why not save the QueryString or whatever data was used to populate the gridview and rebind the data accordingly?
For instance if your user navigates to mypage.aspx?id=56&size=large&date=yesterday
you could load those options in a json object {"Id":"56","size":"large","date":"yesterday"} and store that in the database. Then, your data is up-to-date, and large datasets don't fill up your database table with redundant/outdated data.
Check out: http://www.codeplex.com/Json
edit: and if you don't want to mess around with adding json, you can use anything as a delimiter, for example, have key/value pairs on separate lines and separate them with a pipe ('|')