|
-
Jun 27th, 2009, 10:20 PM
#5
Re: Save to setting status of control
To get one thing clear to begin with, there's only one Settings. When you bind application settings in the designer you're using the same setting as you would be if you used My.Settings in code.
Now, as far as saving the contents of a ListBox, I would suggest that you use a StringCollection in your Settings. You can bind that directly to your ListBox in code if you want. That said, if the list is changing then I'd suggest that you create BindingList from the StringCollection first, then bind the BindingList to the ListBox. You can then add, edit and remove items in the list and, at shutdown, copy the list contents of the BindingList back to the StringCollection for saving. There's no need for you to explicitly save the StringCollection because it will be saved automatically at shutdown, along with all your other settings.
vb.net Code:
Imports System.ComponentModel Imports System.Collections.Specialized Public Class Form1 Private listItems As New BindingList(Of String) Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Create the settings collection on the first run. If My.Settings.ListItems Is Nothing Then My.Settings.ListItems = New StringCollection End If 'Load the data from the settings. For Each listItem As String In My.Settings.ListItems Me.listItems.Add(listItem) Next 'Display the data. Me.ListBox1.DataSource = Me.listItems End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 'Add a new item. Me.listItems.Add(Me.TextBox1.Text) Me.listItems.ResetItem(Me.listItems.Count - 1) End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click If Me.ListBox1.SelectedItem IsNot Nothing Then 'Edit the current item. Me.listItems(Me.ListBox1.SelectedIndex) = Me.TextBox1.Text Me.listItems.ResetItem(Me.ListBox1.SelectedIndex) End If End Sub Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click If Me.ListBox1.SelectedItem IsNot Nothing Then 'Delete the current item. Me.listItems.RemoveAt(Me.ListBox1.SelectedIndex) Me.listItems.ResetItem(Me.ListBox1.SelectedIndex) End If End Sub Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed 'Clear the old data. My.Settings.ListItems.Clear() 'Save the current data. For Each listItem As String In Me.listItems My.Settings.ListItems.Add(listItem) Next End Sub End Class
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|