I don't want to reconnect to a sql server to repopulate every time the page is reposted, but I get a page not found error in my browser when I try this.
Printable View
I don't want to reconnect to a sql server to repopulate every time the page is reposted, but I get a page not found error in my browser when I try this.
Datatables could be saved to viewstate if they exposed a WriteXML property, however they don't.
But DataSets do.
VB Code:
Dim ds As New DataSet ds.tables.add(mytable) 'then serialize the dataset
To serialize a dataset to viewstate involves the following steps:
1) In the PreRender or somewhere applicable, Write the Dataset to an XML string using DataSet.WriteXML
2) Store that string in your page's viewstate.
3) On postback, in the Load_Event, retrieve the XML string from your viewstate.
4) Use DataSet.ReadXML to retrieve the structure and data
VB Code:
Public Sub SmartSerialize() Dim sw As New System.IO.StringWriter DataSet1.WriteXml(sw, XmlWriteMode.DiffGram) Me.ViewState.Add("mydataset", sw.ToString) End Sub Public Sub SmartDeSerialize() Dim sr As New System.IO.StringReader(Me.ViewState("mydataset")) DataSet1.ReadXml(sr, XmlReadMode.DiffGram) End Sub
So of course, you need a reference variable for your dataset (I used a page-scope variable Dataset1 in my exapmle above), and on Page_Load check if it is a postback, if not, get the data from the database or wherever, if it is a postback, get the data from viewstate.
Actually, my internet connection went down and I had to solve this on my own. I read the table into a hashtable and put the hashtable into the viewstate.... Your solution looks pretty good too... I'll file it away.