Share This!

Tuesday, September 7, 2010

Easy XML Dataset Tutorial in Visual C# Express

Create the Data Definition
First, create a new application.
 Add a dataset
Right-click in the stripes and add a datatable.
Right click the datatable to add all the columns you want.
Use the Properties form to set column properties.
Repeat until your table is complete.

Continue this until your dataset is complete.  You can add as may tables as you like.  Keep in mind that you are not creating a database (as you would in SQL Server), you're creating a data definition or schema.

Ok, now to use the dataset in your program.
Set up for Editing
From the top menu, select data - show data sources.
Now, just drag a table from the list to your form.
Notice that a number of components are added to your form when you do this...

Now it's time to hook up the UI to a dataset.  First, enable the save icon in the toolbar.

Next, construct the file/save routine.



Now it's time to tell the dataset how to load the data on startup.  Select the dataset and add an Initialized handler.
The trick here is to make sure the xml file exists before loading it.








Now run the program, and enter data.
 Click the SAVE icon, and exit the program.  Then launch it again to verify that the data has been saved.  Simple, eh?
But, where is my XML file?
Since you ran the application in debug mode, your xml data file was created in that directory.  From the C# IDE menu, select File - Open File... and select bin, then debug.  Your xml file is there, and should look a lot like this:

If you want to know more, like how to read/write data to this kind of dataset in code - just leave me a comment!


Bryan Valencia is a contributing editor and founder of Visual Studio Journey.  He owns and operates Software Services, a web design and hosting company in Manteca, California.

1 comment:

  1. Hello! Thank ya for a wonderfull instructions!
    I would like to know more, like how to "sync" data in different tables with relations, if it is possible.

    For example, if I delete a row with data from "UserInfo" table, the record with same username should be automaticly deleted from "Transactions" table.

    ReplyDelete

Contact Us

Name

Email *

Message *