Application Settings in VB 2005 | |
by Ged Mead | Published 10/24/2006 | .NET Newbie , Visual Basic 2005 , Win Forms | Rating: | |
Introduction
Introduction Application and User Settings have been given a facelift in VB2005. One of the questions that has appeared in VBCity Forums many times over the past few years is the one where someone wants to know how to save user choices, UI settings or other small items of data that have been input by users. Traditionally, going back to Classic VB days this has been done by using the SaveSettings and GetSettings functions which access the Registry to write and read back the data. This approach still works and can be used in all versions of VB.NET, including 2005. While it's not difficult to use, I've never thought of it as particularly intuitive either. So it's good to see that in Visual Studio 2005 there is a very easy to use visual feature available from the Project Properties tab. You are then able to navigate through the available settings in code with ease, thanks to the My.Settings feature. The examples shown in this article are designed for Beginner Level developers as an introduction to the topic. Fire up a new VB 2005 Windows Forms Project and we'll put My.Settings through its paces. Accessing the Settings Editor at Design Time You can use the Settings Editor at design time to set up the names and Types of data for which you want to be able to store settings. To access this editor, use your favourite technique to get to the project's Properties window, e.g. by right clicking the project name and selecting "Properties": or from the main menu: The initial view of the Settings Tab in the Project's property Pages will look like this: Creating new Settings is a very easy process as we will see. | |
Create Settings
Demonstration Settings As a demonstration task, we will add three new Settings. The first will store a user's chosen user name, the second will save the user's choice of form color and the third will optionally allow the user to save the size of the form as the user's chosen values. User Name Click on the first line of the Settings Grid and double click on the first item in the Name Column (which by default is named "Setting") to highlight it. Now overtype "Setting" with "UserName". Leave the Type column item at the default of "String" and the Scope at the default of "User". All that remains is to add a default value for this string. Type in the word "Anonymous". The screenshot below shows these steps completed: You might notice that the Settings are also displayed in a standard Visual Studio Properties Window at the bottom right of the IDE. Settings can be edited in the normal way here as well as in the Settings grid. Form BackColor To demonstrate saving a Setting of a different Type, the next line will be used to enter the details of the Form's BackColor. The screenshot below shows the Settings used. You simply click on the down arrow to the right of the Type and select System.Drawing.Color from the drop down list. Click anywhere inside the Value cell and a small down arrow will appear. Click this in order to view the standard three-tab color choices list. Form Size Finally, add a third Setting named FormSize, select the System.Drawing.Size Type from the dropdown list and type in your chosen values for width and height in the Value cell. I have purposely made the form size quite small so as to encourage the user to change it and then save it.
Applying and Saving The Settings
Put Controls on a Form In Solution Explorer select the default Form1 and view it in the Design Window. Drag controls on to the form as shown below: You can see the suggested names for the controls in the screenshot. These are the names used in the code samples which follow. I have also renamed the form to FrmSettings. Applying Settings on StartUp The usual approach is to apply all saved settings when the application first runs which in this case means that the main form, FrmSettings is loaded. As you will see, we need to refresh the controls from these settings at different times by using some of the various controls. So instead of putting the code into the Form_Load event (and later having to repeat it in, for example a Button_Click event) we will simply place the code in a procedure that we can call when needed. Here is that code: Private Sub ApplyTheSettings() Now, you can call that Sub from the Form_Load event: Private Sub frmSettings_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load ApplyTheSettings() Populating The ComboBox The next piece of code isn't part of the Settings procedures, but is a neat way of listing all the known colors in a ComboBox. You can just copy and paste it into the Form's Load event. Dim ColorChoice As String Changing Values If you now run the project you will see that the TextBox has the default UserName of "Anonymous" and the ComboBox is populated with all the known colors. The next step will be to write code that will change the backcolor of the form to any color the user decides to select from the ComboBox. Again, this is fairly basic non-Settings related stuff: Private Sub cboColors_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboColors.SelectedIndexChanged ' Apply the chosen color as the Form's BackColor End Sub Try running the project, type in a different user name and select a different color from the ComboBox. When you select a different color, the Form's BackColor will change accordingly. Note however that at this stage the My.Settings are not changed. In other words, this isn't an automatic update kind of situation. Just to confirm that, close down the project after making those changes and then immediately run it again by pressing the F5 key. As you will see, your changes haven't been saved. Your user name is still Anonymous and the color is still that rather unexciting Olive Drab. Saving Settings Saving your Settings is not difficult. Each of those names (UserName, FormColor and FormSize) that you assigned at the start are saved as Properties in My.Settings. As a result, as soon as you type: My.Settings. In the code window for the Form, Intellisense will appear and offer you a list which will include all three of those properties.
You could offer the user the choice of when to save the some or all of the Settings, maybe by means of a Button or, as in our example, a CheckBox. For the purposes of this article we will write code to automatically save the UserName and FormColor Settings, but will give the user the choice of whether to save the FormSize also. The most logical place to put this code is when the form is about to close, which in this particular project also means as the application itself is about to close. In VB 2005 this is the FormClosing event. Take a look at the following code: Private Sub frmSettings_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing ' If user wants to save current size: It saves the FormColor setting regardless. It saves the UserName as long as there is a name in the TextBox to save (you may want to remove the "If" part of that line if you are happy for the user to save a name that is just an empty string). Finally, if the user has checked the CheckBox to indicate that the FormSize is to be saved then this too is persisted to the Settings. You can create a whole range of Settings, not limited to just one form. You can apply, for instance, the FormColor choice to all forms in the project or just one form. You can save different BackColors for different forms; or you can save BackColors of some forms, but not of others. It's all about what you want to do to make your application as usable as possible. Reload and Reset
Reload The Reload method can be useful, particularly in situations where the user may want to test out various settings, colors, sizes, etc before deciding which one they most like. What happens when this method is called is that the most recently saved version of the Settings are applied. In the case of our example project, this will be the settings that were saved when the application was last closed down. The following code in the Click event of the Reload Button will replace any unsaved changes with the version that was last saved: Private Sub btnReload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReload.Click As you can see from the comments in the code snippet above, you still need to implement the code which applies the Settings. That is, the Reload method itself will reload the saved values into memory but they are not automatically applied to - in our example - the BackColor, the Size and the UserName. This is actually often quite a good thing because there may well be times when you only want to reload some of the saved Settings but not others. There are various solutions for this, the most obvious one being that you create an alternative version of ApplyTheSettings (maybe called ApplySomeSettings) and only assign the reloaded values to those controls that you want changed. I'm sure you will also have realised that you can use an approach of:
which will work just as well and may cause less confusion than having several variations of the Apply***Settings procedures around the project. Reset Settings Not to be confused with Reload, the Reset method reaches right back to those initial settings that you applied right at the start of the project's life. It will load them into memory and the code below will apply them all. The discussion above about how to apply the new values to only some Settings is also relevant to the Reset method and the same workarounds can be used. The code for the Reset button is very similar to that for Reload: Private Sub btnReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReset.Click End Sub Note however that if you implement the Reset method, the original values will automatically be saved as if these were the user's last saved values. In other words, previously user saved values will be overwritten by these reset initial values If you are not quite sure what I mean by that, try running the demo project a few times, then use the Reload button, followed by the Reset button, finally followed by the Reload button once again. You will then see what I mean. Summary
This article is intended to be a first pass at using My.Settings which is aimed at VB 2005 Beginners. It is of course possible to drill down far deeper into this topic and hopefully I will be able to cover this in a later article.
For the time being though, you now have the means to create, save, edit and access a whole range of Settings for your VB 2005 projects. I hope you find this introduction to the subject to be useful to you.
|
正文
VB2005的程序设置2006-11-11 11:08:00
【评论】 【打印】 【字体:大 中 小】 本文链接:http://blog.pfan.cn/iamben250/20190.html
阅读(2987) | 评论(0)
版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!
评论