views:

410

answers:

3

Hi everyone,

I am wondering if it's possible to add data to a DataTable through a DataGridView and save the data in the DataTable by serializing it--and all of this without having to create an underlying database. One DataTable is sufficient for the amount of data I am trying to store and a database is definitely overkill.

Thanks!

+1  A: 

I don't think I understand you question about the serialization.

If you assign a DataTable to a DataGridView DataSource property, when you input data in the form, it will be automatically added to the DataTable.

If you want to persist the data inside the DataTable outside a DB, you should use the DataTable WriteXml() method (and ReadXml() to load the data). As you see, the data is serialized in xml format.

Gerardo Contijoch
Agreed, Serialization is an alternative but I would go for WriteXML, maybe to a CompressionStream.
Henk Holterman
A: 

Thank you! I will try this.

A: 

Not only possible but pretty straightforward. I am going just that with a dataset containing datatables that use datagridviews for input. The dgv use bindingsources as their data source and the bindingsource has the dataset as a its datasource and datatable as datamember.

I serialize the dataset to a varbinary(max) column in SQL Server.

( I use strongly typed properties on my business object, but this should give you the idea )

    '-- Copy dataset to property

    '-- Establish locals
    Dim loFormatter As New BinaryFormatter()
    Dim loStream As New System.IO.MemoryStream()

    '-- Serialize the business object
    loFormatter.Serialize(loStream, Me.DsPolicies1)


    '-- Return the created stream
    Me.PoliciesBO1.Dataset_Bytes = loStream.ToArray()

When the policy record is navigated, the property is deserialized

      If Me.PoliciesBO1.Count > 0 And Me.PoliciesBO1.CurrentRowIndex >= 0 Then

            Me.clear_bindingsources()

            Dim loformatter As New BinaryFormatter()
            Dim lomemorystream As MemoryStream = _
               New MemoryStream(Me.PoliciesBO1.Dataset_Bytes, 0, _
               Me.PoliciesBO1.Dataset_Bytes.Length, True)

            Me.DsPolicies1 = _
                  CType(loformatter.Deserialize(lomemorystream), dsPolicies)

            '-- Rehook datasource 

            Me.rehook_Bindingsources()

            Me.refresh_dgvs()

The last two subs just reset the bindingsource datasource and datamember for each table and then refresh each dgv

( I use these for data gathering to fill PDF Forms )

The only tricky part is remembering the datasource has to be empty on a new record and must be completely reloaded from data after a "parent" record pointer moves.

Charles Hankey