ASP.NET VERSIONS: 2.0
What s New in Windows Forms 2.0: Part I
By Wei-Meng Lee
With the release of Microsoft Visual Studio 2005, a lot of media attention has been focused on the new and improved ASP.NET 2.0. However, a lot of improvements have also been made on the other side of the fence; in this case, Windows Forms 2.0. In this two-part article, I ll walk you through some of the new and cool features in Windows Forms 2.0 and how you can take advantage of them in your next application.
One significant improvement in the Windows Designer is the support for Snaplines. When you position a control on a Windows form, lines known as Snaplines will be shown to help you position the control in the correct place on the form. Figure 1 shows two lines in blue showing you the recommended distance to position the Button control from the edges of the window.
Figure 1: Snaplines showing the recommended distance from the edges of the window.
Snaplines also help you align multiple controls. Figure 2 shows how two controls can be aligned either based on the lower edge of the control or based on the text contained within the control.
Figure 2: Aligning controls using Snaplines.
Data-binding is another area which is much improved in Windows Forms 2.0. To see the new data-binding feature in action, I will walk you through a simple example. For this example, let s create a Windows application using Visual Studio 2005 and name it WindowsForms2.0.
To use data-binding, first add a data source to the project by going to Data | Add New Data Sources. In the Choose a Data Source Type dialog box (see Figure 3), select Database and click Next. Note that you can also data-bind to a Web service or business object.
Figure 3: Selecting a data source.
In the Choose Your Data Connection dialog box, click the New Connection button (see Figure 4) to establish a connection to the database you want to use.
Figure 4: Establishing a new data connection.
Enter the name of the database server (I will use the default-installed SQL Server 2005 Express database that comes with Visual Studio 2005) and select the Northwind database (see Figure 5). Click OK.
Figure 5: Selecting the database and table.
Unlike SQL Server 2000, SQL Server 2005 Express and SQL Server 2005 do not come with the default sample databases. If you would like to install the sample databases on these servers, you can download them from http://www.microsoft.com/downloads/details.aspx?FamilyID=06616212-0356-46a0-8da2-eebc53a68034&displaylang=en.
When back in the Choose Your Data Connection dialog box, click Next. You will be prompted to save the connection string of the database into the application configuration file (see Figure 6). Click Next.
Figure 6: Saving the connection string into the application configuration file.
In the Choose Your Database Objects dialog box, expand the Employees table and check the fields shown in Figure 7. Click Finish.
Figure 7: Selecting the fields and tables to use.
You can now view the newly added data source by going to Data | Show Data Sources (see Figure 8).
Figure 8: Viewing the newly added data source.
If you have upgraded from a previous version of Visual Studio 2005 (such as Visual Studio 2005 Beta 2, or one of the various CTP releases), you may encounter the situation where the Data Sources window is empty after adding a new data source. To resolve this known issue, check out the following link: http://lab.msdn.microsoft.com/ProductFeedback/viewFeedback.aspx?feedbackid=23c8516f-aba6-487e-bbeb-7c3d20ef60e9.
If you click on the drop-down button on the Employees table, you ll see that it is bound to the DataGridView control. This means that when you drag the employees table onto a Windows form, a DataGridView control will be added to the form to display the content of the Employees table. For now, let s change the binding to Details (see Figure 9). Also, change the EmployeeID field to a Label control (since this field should not be modifiable) and the Photo field to a PictureBox control (to display the image of the employee).
Figure 9: Changing the default binding of the table and its fields.
Drag and drop the Employees table from the Data Sources window onto a Windows form. Figure 10 shows what the form looks like after the operation. Also notice that there are four new controls added to the form. These controls perform the necessary data-binding between the database and the controls on the form.
Figure 10: Dragging and dropping the data source onto a form.
For the PictureBox control, set the SizeMode property to AutoSize so that the control can automatically resize according to the image.
Press F5 to test the application. You will now be able to navigate between the records in the table by clicking on the navigational bar located at the top of the window (see Figure 11).
Figure 11: Testing the application.
You can also make changes to the records by directly modifying them in the text boxes. To save the changes, click the Save icon (represented by the diskette icon).
To add a new record, click on the + button, then the Save button. To delete a record, click the x button, then the Save button.
Notice that we have not written a single line of code and all this is done automatically for us. Amazing!
The new Application Settings feature in Windows Forms 2.0 makes it a breeze for developers to persist personalized information for each user, as well as information for the application.
Using the Application Settings feature, you can save the state for an application without needing to write the plumbing code to save and read the information from disk.
As an example, let s use the Application Settings feature on our previous project to save the last record that is shown on the form so that the next time the application is loaded, the last record is shown.
To do so, let s add an application setting to the project. Right-click on the project name in Solution Explorer and select Properties. On the Settings tab, add a new setting and name it CurrentRecord (see Figure 12). Set its data type to Integer and use the scope of User. Save the project.
Figure 12: Adding a new application setting to the project.
Notice that there already exists a setting called NorthwindConnection. This setting was created earlier when you added a new data source. There are two scopes for application settings:
- Application. An application-scope application setting is specific to the entire application. This scope is useful for information specific to the application, such as a database connection string, Web services settings, etc.
- User. A user-scope application setting is specific to individual users. This scope is useful for persisting user-specific information, such as the size of the form, preference settings, etc.
For our sample application, we will save the position of the current record when the form is closed. To do so, code the FormClosing event of the form, as follows:
Private Sub Form1_FormClosing( _
ByVal sender As Object, _
ByVal e As System.Windows.Forms.FormClosingEventArgs) _
My.Settings.CurrentRecord = EmployeesBindingSource.Position
Notice that the CurrentRecord application setting you created can be accessed directly from the My.Settings namespace (if you don t see the CurrentRecord setting appearing under My.Settings in IntelliSense, then you most probably have not saved the project yet).
When the application is loaded again, we will restore the position of the record by retrieving the value from the application setting:
Private Sub Form1_Load( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into
'the 'NorthwindDataSet.Employees' table.
'You can move, or remove it, as needed.
EmployeesBindingSource.Position = My.Settings.CurrentRecord
By default, when you assign a value to an application setting, it is saved automatically when the application is shut down. This can be verified by viewing the Application tab in the project properties window (see Figure 13).
Figure 13: Automatically saving My.Settings on application shut down.
If the Save My.Settings on Shutdown checkbox is unchecked, you can explicitly save the application settings by calling the Save method:
But where are the values of the application settings stored? For user-scope application settings, the values are stored in the user.config file (see Figure 14) located in directories deeply nested within the C:\Documents and Settings\Wei-Meng Lee\Local Settings\Application Data\ folder. For application-scope application settings, they are stored in the app.config file usually deployed together with the application.
type="System.Configuration.UserSettingsGroup, System, Version=18.104.22.168, Culture=neutral, PublicKeyToken=b77a5c561934e089" > type="System.Configuration.ClientSettingsSection, System,
Version=22.214.171.124, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
System, Version=126.96.36.199, Culture=neutral,
Figure 14: The contents of the user.config file for our application.
One very useful new feature in Windows Forms 2.0 is the application events handlers. To view all the application events, click the View Application Events button on the Application tab (see Figure 15).
Figure 15: Viewing the application events.
The ApplicationEvents.vb file contains the code for servicing the various events in the application. The following events are supported:
- NetworkAvailabilityChanged. Occurs when the availability of the network changes.
- Shutdown. Occurs when the application shuts down.
- Startup. Occurs when the application starts.
- StartupNextInstance. Occurs when attempting to start a single-instance application and the application is already active.
- UnhandledException. Occurs when an exception is not caught by an event handler.
You can add the event to service by selecting the events from the drop-down list located at the top of the window (see Figure 16). As an example, if you want to ensure that only one instance of your application can run at any one time, select the StartupNextInstance event.
Figure 16: Setting the application events to service.
Also check the Make single instance application checkbox, as shown in Figure 15. This will ensure that when another instance of the application is executed, the StartupNextInstance event will be fired. This event is useful for cases where you want to allow a single instance of your application to run on a client s machine.
Code the StartupNextInstance event handler as follows:
Private Sub MyApplication_StartupNextInstance( _
ByVal sender As Object, _
ByVal e As Microsoft.VisualBasic.ApplicationServices. _
StartupNextInstanceEventArgs) Handles Me.StartupNextInstance
MsgBox("Another instance of the application is " & _
" already running. Application will now exit.")
When you try to run more than one instance of the application, the message box shown in Figure 17 will appear.
Figure 17: Displaying the error message when trying to start another instance of an application.
In this article, you have seen some of the new productivity features of Windows Forms 2.0. In particular, you have seen how the visual designer uses Snaplines to help you position your controls. You have also learned how to use the data-binding capabilities of Windows Forms 2.0 to display records on your form without writing a single line of code. Last but not least, the Application Settings feature allows you to persist application state easily by providing all the plumbing code needed. As you can see, all these new features save you lots of effort in writing code usually required for mundane tasks, freeing you to spend more time to add features to your application.
In Part II we ll look at the new deployment technology known as ClickOnce, as well as discuss a new feature known as RegFree COM and how it can be used together with ClickOnce to simplify your deployment tasks. We ll wrap things up with a look at some new and improved Windows controls and how you can use them to create professional Office-like applications.
Wei-Meng Lee (http://weimenglee.blogspot.com) is a technologist and founder of Developer Learning Solutions, a technology company specializing in hands-on training on the latest Microsoft technologies. Wei-Meng speaks regularly at international conferences and has authored and coauthored numerous books on .NET, XML, and wireless technologies, including ASP.NET 2.0: A Developer s Notebook and Visual Basic 2005 Jumpstart (both from O Reilly Media, Inc.).