Click here to Skip to main content
15,867,453 members
Articles / Desktop Programming / Windows Forms
Article

Save your WinForms User Control Data to XML

Rate me:
Please Sign up or sign in to vote.
3.80/5 (4 votes)
19 Oct 2006CPOL4 min read 58.6K   1.3K   35   9
Allows the developer to save all of the data in user controls in a WinForms app

Introduction

Since this is my first attempt at an article, I would ask that you please be gentle with your comments. ;-)


This class gives the developer the ability to save all of the data on a windows form to an XML file stored on the user's local machine. This would be useful if the user was entering alot of duplicated data in a large form and wanted to save the information to prevent having to type it out each time.

Background

I actually wrote this code in 2005 to handle a request from a user. She said that she wanted to be able to save all of the data on her form to an XML file and have it automatically read back in when she opened up the form the next time.


Although this class only saves information for a windows form, I would not think it to be too difficult to save the same type of info for a web form. It would be a little difficult determining where to save the file full of XML data, but it could be done. Please, if you want to do that, feel free to modify my code and add the code to this class and post it back up here.

Using the code

There are a couple of procedures that the developer needs to use. To have this class work properly, you will need to make sure that you set the properties of the class to "True" for each type of control that you want the data saved as.

VB.NET
#Region " Public Properties"
     Public Property SaveTextBox() As System.Boolean
        Get
            Return mbSaveTextBox
        End Get
        Set(ByVal value As System.Boolean)
            mbSaveTextBox = value
        End Set
    End Property

    Public Property SaveComboBox() As System.Boolean ...

    Public Property SaveRadioButton() As System.Boolean ...

    Public Property SaveCheckBox() As System.Boolean ...

#End Region

As you can see, the properties are very simple and only meant to turn on/off the ability for the code to save that type of control's data. There are plenty of other controls that could be added here, but I have had no need for them yet.


Let's take a look at the code that is actually used to save and load the XML from the filesystem. I found that we had some initial trouble with controls that were contained in frames (not the ones for websites, but the frame control for WinForms). Check it out...

Public Sub SaveData(ByVal oParentForm As System.Windows.Forms.Form)

VB.NET
msFileName = CType(Application.LocalUserAppDataPath.ToString &_<BR>             "\" & oParentForm.Name.ToString & "_FormData.xml", System.String)

If File.Exists(msFileName) Then

    Try
        File.Delete(msFileName)
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End If

First, we set a filename to the AppPath's file and the name of the form that we are looking for. We can then use that filename to process each control on the form and save the data, if we set it up to do so. Then, we open the XMLTextWriter to start writing the document...


VB.NET
oTextWriter = New XmlTextWriter(msFileName, _<BR>                                         System.Text.Encoding.UTF8)

With oTextWriter
    .WriteStartDocument(True)
    .WriteStartElement("Controls")
End With

Next, we will iterate through the entire form's controls collection and see if we are supposed to save the data. If we are, we write the line to the XMLTextWriter.


VB.NET
For Each oControl In oParentForm.Controls

    If TypeOf oControl Is Panel Or TypeOf oControl Is GroupBox Then
        Dim oContainer As Control
        Dim oChild As Control
        oContainer = oControl

        For Each oChild In oContainer.Controls
            If TypeOf oChild Is GroupBox Then

                Dim oGroupBox As Control
                oGroupBox = oChild
                Dim ochild2 As Control

                For Each ochild2 In oGroupBox.Controls
                    checksavecontrol(ochild2)
                Next
            Else
                checksavecontrol(oChild)
            End If

        Next

    Else
        checksavecontrol(oControl)
    End If
Next

The CheckSaveControl() function will determine if the control type's data should be saved to the file system. If it is, it writes the data to the XMLTextWriter.


After we have looked at all of the controls on the form, we close the XMLDocument up and close out the XMLTextWriter.


VB.NET
   With oTextWriter
       .WriteEndElement()
       .WriteEndDocument()
       .Flush()
       .Close()
End With

The load function took a little more work. We have to iterate through all of the controls on the form as well, but we also have to make sure that they are not container controls. If they ARE containers, we have to loop through the container's controls collection and save that data as well.


This posed a problem when I first worked on it. We had a form that was trying to save the data and the control was setup to be saved, but the data wouldn't work. It turned out that we had nested container controls. There was a group box inside of a frame. This gave me a headache for hours until I noticed on the form's Design View what was going on! Keep your eye out for those nested container controls!

Possible Enhancements

Like I said, you could potentially use this in an Web app environment using a user's GUID instead of the Application.LocalUserAppPath and save the file to a directory that holds all of the user data.


If you come up with anything that needs corrected, let me know!  Thanks to GlimmerMan for pointing out that I forgot to finish the Load Event!!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
I have been working with VB since verion 3.0 in 1993. I have used every version since then, including all 3 releases (so far) of VB.NET. I am a Microsoft Certified Application Developer and, of course, an MCP. I am a programmer analyst for a web development company currently and try to get out golfing when not coding!

Comments and Discussions

 
GeneralMy vote of 5 Pin
aalhanane8-Dec-11 10:35
aalhanane8-Dec-11 10:35 
GeneralThank you very much. It is exactly what I needed. Pin
koke178-Feb-11 5:19
koke178-Feb-11 5:19 
GeneralPossible Upgrade Pin
aaroncampf20-Nov-10 11:13
aaroncampf20-Nov-10 11:13 
GeneralMy compliments and an alternative Pin
Edwin Roetman24-Oct-06 5:06
Edwin Roetman24-Oct-06 5:06 
QuestionDid I miss something? Pin
karenpayne17-Oct-06 8:03
karenpayne17-Oct-06 8:03 
AnswerRe: Did I miss something? Pin
JamminJimE19-Oct-06 10:59
JamminJimE19-Oct-06 10:59 
GeneralRe: Did I miss something? Pin
karenpayne19-Oct-06 11:22
karenpayne19-Oct-06 11:22 
GeneralGood work Pin
mina_73010-Sep-06 22:54
mina_73010-Sep-06 22:54 
I think the problem of containers can be solved by using recursive function.
thx for ur work

MinaEGYPT
GeneralRe: Good work Pin
JamminJimE12-Sep-06 2:56
JamminJimE12-Sep-06 2:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.