views:

72

answers:

3

On my main window I have a DataGridView that I wish to display my data. My application allows users to input, change, and delete data. I asked my friend the best method of doing this he said storing the information in an XML file. So now I am wondering on HOW to use XmlSerializer. Can I make an XML document or DataSet and give it values, but still be able to read, add, and change those values (via DataGridView)? Also, I would like to check if the XML file is created (if it is the first time the application is executed, create the xml; if not, use created xml file).


Also make sure it's in C#!

+1  A: 

See this question about using XML as a datasource for a DataGridView

Stuart Dunkeld
A: 

Here is an example VB.NET app that opens an XML file by reading it into a DataSet, then assigns the DataTables created in the DataSet as the source for a DataGridView. It lets you edit and add rows to the grid view, then saves it back to the XML file:

http://dot-dash-dot.com/files/wtfxml.zip

Ron

Ron Savage
Great, but I prefer C#.
Mohit Deshpande
It's pretty easy to convert to C#, all the .NET objects are the same. Mostly it's adding ";" to the end of lines changing "dim var as type" to "type var". :-)
Ron Savage
I am talking about using XMLSerializer to create an xml file, not using a pre-existing one. Most of my classmates don't even know what an XML file is.
Mohit Deshpande
Ah! Usually, most data is easier to envision as a table or multiple tables. You can create those in a DataSet (adding DataTables made of DataColumns and adding DataRows) then save them to an XML file with DataSet.WriteXML(). If you prefer attributes to elements, set the DataColumns mapping style to be Attributes.
Ron Savage
A: 

Depends how much control you want over the XML, but something like this should give you the idea:

    DataTable dt = new DataTable("MyTable");
    dt.Columns.Add(new DataColumn("MyCol1", typeof(string)));
    dt.Columns.Add(new DataColumn("MyCol2", typeof(int)));

    DataSet ds = new DataSet();
    ds.Tables.Add(dt);

    dt.Rows.Add("Val1", 5);
    dt.Rows.Add("Val2", 6);

    ds.WriteXml("data.xml");

    DataSet ds2 = new DataSet();
    ds2.ReadXml("data.xml");

Not using XmlSerializer (directly), though.

Wayne