Click here to Skip to main content
15,886,756 members
Articles / Desktop Programming / Windows Forms

Load and Save Data Using PropertyGrid

Rate me:
Please Sign up or sign in to vote.
3.69/5 (8 votes)
27 Jun 2008CPOL2 min read 52.1K   28   6
A simple example of loading, saving, and displaying objects in a PropertyGrid using serialization techniques.

Introduction

I've recently been researching the PropertyGrid control in Visual Basic 2008. There is a lot of information out there, mainly for C# programmers. After quite a bit of research and the inevitable false starts, I came upon a response to a question on a website which looked like the answer to a common question: How do I load and save information into a PropertyGrid using VB.NET? Unfortunately, the posting was a little cryptic. With a little tweaking, I came up with the following fully functioning example, and thought I'd share it with everyone.

Background

The following example was developed and tested using Windows Vista and Visual Basic Express Edition 2008, running on the .NET 3.5 Framework with Internet Explorer version 7. It should work with previous versions of these systems.

Using the Code

The example uses serialization to load and save a class object to and from an XML file. In order to achieve this, you simply add the attribute <Serialize()> to the class identifier, as follows:

VB
<Serializable()> _
Public Class AppSettings

You need to add two functions/methods to the class object you are defining which provide the load and save functionality. In the full example below, these are called:

VB
Public Shared Function Load() As AppSettings

and

VB
Public Sub Save()

You then simply include the following code in your main class to alternatively load or save the class object into your PropertyGrid:

VB
Public Class Form1
    'Load AppSettings
    Dim _appSettings As New AppSettings()

    Private Sub Button1_Click(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles Button1.Click
        _appSettings = AppSettings.Load()
        ' Actually change the form size
        Me.Size = _appSettings.WindowSize
        PropertyGrid1.SelectedObject = _appSettings
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles Button2.Click
        _appSettings.Save()
    End Sub
End Class

To run the complete example which follows, create a form with a PropertyGrid and two Buttons. On clicking the LOAD button, we load an XML file with the window size saved (if the file already exists). If it doesn't already exist, the program sets the window width and height to 600 by 600. This information is then loaded into the PropertyGrid. We can now modify the window size values in the PropertyGrid. Clicking on the SAVE button serializes the information in the PropertyGrid and saves the values to an XML file on disk. If you now close the program and then re-run it, when you click on the LOAD button, the values you previously entered into the PropertyGrid are re-loaded and displayed.

Follow these steps to create the example:

  1. Create a new project in VB.NET 2008
  2. Display your form (called Form1) in Design mode
  3. Add a PropertyGrid control
  4. Add a Button control and change the Text property to LOAD
  5. Add a second Button control and change the Text property to SAVE

Now, switch to the code editor and change the Form1 code from:

VB
Class Form
End Class

to the following:

VB
'==============================================
'How to serialize, load and save a class object
'==============================================
Imports System.Xml.Serialization
Imports System.IO

Public Class Form1
    'Load AppSettings
    Dim _appSettings As New AppSettings()

    Private Sub Button1_Click(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles Button1.Click
        _appSettings = AppSettings.Load()
        ' Actually change the form size
        Me.Size = _appSettings.WindowSize
        PropertyGrid1.SelectedObject = _appSettings
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles Button2.Click
        _appSettings.Save()
    End Sub
End Class

<Serializable()> _
Public Class AppSettings
    Protected _size As System.Drawing.Size

    Public Property WindowSize() As System.Drawing.Size
        Get
            Return _size
        End Get
        Set(ByVal value As System.Drawing.Size)
            _size = value
        End Set
    End Property

    Public Shared Function Load() As AppSettings
        Dim serializer As XmlSerializer = New XmlSerializer(GetType(AppSettings))
        Dim retVal As AppSettings
        Dim reader As TextReader
        Dim fileNotFound As Boolean

        Try
            reader = New StreamReader("MyAppSettings.xml")
        Catch ex As FileNotFoundException
            ' Take the defaults
            fileNotFound = True
        End Try

        If fileNotFound Then
            retVal = New AppSettings
            retVal.WindowSize = New System.Drawing.Size(600, 600)
        Else
            'Read it from the file
            retVal = serializer.Deserialize(reader)
            reader.Close()
        End If

        Return retVal
    End Function

    Public Sub Save()
        Dim serializer As New XmlSerializer(GetType(AppSettings))
        Dim writer As TextWriter = New StreamWriter("MyAppSettings.xml")
        serializer.Serialize(writer, Me)
        writer.Close()
    End Sub

End Class

Points of Interest

The above code sample is largely based on the response by Christian Lucht to a posting at: SDN Software Development Network.

License

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


Written By
Chief Technology Officer Vobis Consulting Ltd
United Kingdom United Kingdom
I've been around since the beginning of time (well, nearly fifty years anyway), and I've enjoyed programming since the days of DOS 1.0 with assembly language, MS-BASIC, GW-BASIC, QuickBASIC, Visual BASIC and now VB.NET.

Comments and Discussions

 
QuestionGetting error Pin
Ruturaaj V. Patki4-Dec-19 20:38
Ruturaaj V. Patki4-Dec-19 20:38 
Questionsave a button Pin
massimo.valtolina1-Mar-13 10:37
massimo.valtolina1-Mar-13 10:37 
GeneralMy vote of 5 Pin
sayram12-Jan-11 8:49
professionalsayram12-Jan-11 8:49 
QuestionHow would you save color information? Pin
malcomm16-Dec-10 11:47
malcomm16-Dec-10 11:47 
GeneralWow This is sooo cool Pin
aaroncampf29-Nov-10 15:08
aaroncampf29-Nov-10 15:08 
GeneralExcellent code [modified] Pin
l15t1r46-May-09 7:02
l15t1r46-May-09 7:02 

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.