简体   繁体   中英

Windows Forms: Adding an empty DataTable to a Dataset

I currently am working on a Windows forms application in C# and I have a DataGridView that has a data source which is a DataTable. The DataGridView and DataTable are loaded from a DataSet which is stored on disk. If any changes are made in the DataGridView then they are written out to the file when a save button is clicked. However, if all rows are deleted, the next time the program runs and I try to add a row in the DataGridView, it does not get written to the file since when I load it, the DataTable does not exist since all the rows were deleted.

Here is the code:

DataSet ds = new DataSet();
DataTable dt160m = new DataTable("dt160m");
DataTable dt80m = new DataTable("dt80m");

ds.ReadXml(filename);

dt160m = ds.Tables["dt160m"];
dt80m = ds.Tables["dt80m"];

dataGridView160m.DataSource = dt160m;
dataGridView80m.DataSource = dt80m;

Now this is great. If I delete all records from the dataGridView80m for example, then when I reopen it there is no DataTable called dt80m in the DataSet anymore. Adding additional rows will not create the datatable.

Any suggestions to work around this? Thanks.

The problem is in the point where you write back your dataset to disk as an XML file. If one or both of your DataTable is empty then you loose the schema of that table. Fortunately there is an overload of Dataset.WriteXml that takes another parameter.

ds.WriteXml(filename, XmlWriteMode.WriteSchema);

in this way, the resulting file on disk contains always the schema of your tables also if there are no records.

Of course, when you read it back, you get the schema of your tables using

ds.ReadXml(filename, XmlReadMove.ReadSchema);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM