Results 1 to 3 of 3

Thread: Can I save a table in ViewState?

  1. #1

    Thread Starter
    Member
    Join Date
    Dec 2003
    Location
    NYC
    Posts
    50

    Can I save a table in ViewState?

    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.

  2. #2
    I wonder how many charact
    Join Date
    Feb 2001
    Location
    Savage, MN, USA
    Posts
    3,704
    Datatables could be saved to viewstate if they exposed a WriteXML property, however they don't.

    But DataSets do.
    VB Code:
    1. Dim ds As New DataSet
    2. ds.tables.add(mytable)
    3.  
    4. '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:
    1. Public Sub SmartSerialize()
    2.         Dim sw As New System.IO.StringWriter
    3.         DataSet1.WriteXml(sw, XmlWriteMode.DiffGram)
    4.         Me.ViewState.Add("mydataset", sw.ToString)
    5.  
    6.     End Sub
    7.  
    8.     Public Sub SmartDeSerialize()
    9.         Dim sr As New System.IO.StringReader(Me.ViewState("mydataset"))
    10.         DataSet1.ReadXml(sr, XmlReadMode.DiffGram)
    11.    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.

  3. #3

    Thread Starter
    Member
    Join Date
    Dec 2003
    Location
    NYC
    Posts
    50

    Thumbs up Thank you so much....

    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.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width