2

I currently try to save a datatable as a user setting using die old "properties.settings.default.save()" method.

It does not work. My Settings don't get saved. however it does work when I try to save a string as setting.

So I am really wondering why it doesn't work with the datatable. Saving the datatale would make a lot of things easier for me, so any help on that or any alternative solutions would be greatly appreciated!

John Saunders
  • 160,644
  • 26
  • 247
  • 397

3 Answers3

6

You can save the DataTable as an XML string to an ordinary String setting, like this:

 StringWriter writer = new StringWriter();
 table.WriteXml(writer);
 Settings.Default.TableXml = writer.ToString();

You can then load it from the setting like this:

 StringReader reader = new StringReader(Settings.Default.TableXml);
 table.ReadXml(reader);
bonbon.langes
  • 1,718
  • 2
  • 22
  • 37
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

I believe I encountered this same problem while performing a LINQ query on a DataTable from an ERP database. After using the CopyToDataTable() method on the query result and assigning it to the settingTable setting, I verified that neither the resultTable nor the settingTable were null and I ran the Settings.Default.Save() method. However, I received a null error when I subsequently attempted to assign the settingTable to a dataTable variable.

I resolved this problem by assigning the settingTable.TableName property to something other than its default value (the null string) before running the Settings.Default.Save() method.

Note: The ERP system is really slow, I would just query the data directly using the ERP's business objects.

CyanCoding
  • 1,012
  • 1
  • 12
  • 35
0

sadly the solution above doesn't work for me (got an exceptation that the root element is missing). I had to make this adjustments.

Create XML String:

 StringWriter writer = new StringWriter();
 table.WriteXml(writer, XmlWriteMode.WriteSchema); //WriteSchema
 Settings.Default.TableXml = writer.ToString();

Create DataTable from Xml String

 StringReader reader = new StringReader(Settings.Default.TableXml);
 table.ReadXml(reader);

Hope this helps al further users having the same problem ;)