What’s New in Windows Forms 2.0: Part I

Improved Productivity

Wei-Meng Lee

October 30, 2009

10 Min Read
ITPro Today logo

CoverStory

LANGUAGES: ALL

ASP.NETVERSIONS: 2.0

 

What s New in Windows Forms 2.0: Part I

Improved Productivity

 

By Wei-Meng Lee

 

With the release of Microsoft Visual Studio 2005, a lot ofmedia 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; inthis case, Windows Forms 2.0. In this two-part article, I ll walk you throughsome of the new and cool features in Windows Forms 2.0 and how you can takeadvantage of them in your next application.

 

Snaplines

One significant improvement in the Windows Designer is thesupport for Snaplines. When you position a control on a Windows form, linesknown as Snaplines will be shown to help you position the control in thecorrect place on the form. Figure 1 shows two lines in blue showing you therecommended distance to position the Button control from the edges of thewindow.

 


Figure 1: Snaplines showing therecommended distance from the edges of the window.

 

Snaplines also help you align multiple controls. Figure 2shows how two controls can be aligned either based on the lower edge of thecontrol or based on the text contained within the control.

 


Figure 2: Aligning controls usingSnaplines.

 

Data-binding

Data-binding is another area which is much improved inWindows Forms 2.0. To see the new data-binding feature in action, I will walkyou through a simple example. For this example, let s create a Windowsapplication using Visual Studio 2005 and name it WindowsForms2.0.

 

To use data-binding, first add a data source to theproject by going to Data | Add New Data Sources. In the Choose a Data SourceType dialog box (see Figure 3), select Database and click Next. Note that youcan 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 theNew Connection button (see Figure 4) to establish a connection to the databaseyou want to use.

 


Figure 4: Establishing a new dataconnection.

 

Enter the name of the database server (I will use thedefault-installed SQL Server 2005 Express database that comes with VisualStudio 2005) and select the Northwind database (see Figure 5). Click OK.

 


Figure 5: Selecting the database andtable.

 

Unlike SQL Server 2000, SQL Server 2005 Express and SQLServer 2005 do not come with the default sample databases. If you would like toinstall 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 databaseinto the application configuration file (see Figure 6). Click Next.

 


Figure 6: Saving the connectionstring into the application configuration file.

 

In the Choose Your Database Objects dialog box, expand theEmployees table and check the fields shown in Figure 7. Click Finish.

 


Figure 7: Selecting the fields andtables to use.

 

You can now view the newly added data source by going toData | Show Data Sources (see Figure 8).

 


Figure 8: Viewing the newly addeddata source.

 

If you have upgraded from a previous version of VisualStudio 2005 (such as Visual Studio 2005 Beta 2, or one of the various CTPreleases), you may encounter the situation where the Data Sources window isempty after adding a new data source. To resolve this known issue, check outthe 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 Employeestable, you ll see that it is bound to the DataGridView control. This means thatwhen you drag the employees table onto a Windows form, a DataGridView controlwill be added to the form to display the content of the Employees table. Fornow, let s change the binding to Details (see Figure 9). Also, change theEmployeeID 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 theemployee).

 


Figure 9: Changing the defaultbinding of the table and its fields.

 

Drag and drop the Employees table from the Data Sourceswindow onto a Windows form. Figure 10 shows what the form looks like after theoperation. Also notice that there are four new controls added to the form.These controls perform the necessary data-binding between the database and thecontrols on the form.

 


Figure 10: Dragging and dropping thedata source onto a form.

 

For the PictureBox control, set the SizeMode property toAutoSize so that the control can automatically resize according to the image.

 

Press F5 to test the application. You will now be able tonavigate between the records in the table by clicking on the navigational barlocated at the top of the window (see Figure 11).

 


Figure 11: Testing the application.

 

You can also make changes to the records by directlymodifying 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 theSave button. To delete a record, click the x button, then the Save button.

 

Notice that we have not written a single line of code andall this is done automatically for us. Amazing!

 

Application Settings

The new Application Settings feature in Windows Forms 2.0makes it a breeze for developers to persist personalized information for eachuser, as well as information for the application.

 

Using the Application Settings feature, you can save thestate for an application without needing to write the plumbing code to save andread the information from disk.

 

As an example, let s use the Application Settings featureon our previous project to save the last record that is shown on the form so thatthe 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. Onthe 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 applicationsetting to the project.

 

Notice that there already exists a setting calledNorthwindConnection. This setting was created earlier when you added a new datasource. 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 databaseconnection string, Web services settings, etc.

  • User.A user-scope application setting is specific to individual users. This scope isuseful for persisting user-specific information, such as the size of the form,preference settings, etc.

 

For our sample application, we will save the position ofthe current record when the form is closed. To do so, code the FormClosingevent of the form, as follows:

 

Private Sub Form1_FormClosing( _

   ByVal sender As Object, _

   ByVal e As System.Windows.Forms.FormClosingEventArgs)_

   Handles Me.FormClosing

   My.Settings.CurrentRecord =EmployeesBindingSource.Position

End Sub

 

Notice that the CurrentRecord application setting youcreated can be accessed directly from the My.Settings namespace (if you don tsee the CurrentRecord setting appearing under My.Settings in IntelliSense, thenyou most probably have not saved the project yet).

 

When the application is loaded again, we will restore theposition of the record by retrieving the value from the application setting:

 

Private Sub Form1_Load( _

 ByVal sender AsSystem.Object, _

 ByVal e AsSystem.EventArgs) Handles MyBase.Load

  'TODO: This line of codeloads data into

  'the'NorthwindDataSet.Employees' table.

  'You can move, or removeit, as needed.

  Me.EmployeesTableAdapter.Fill(Me.NorthwindDataSet.Employees)

  EmployeesBindingSource.Position = My.Settings.CurrentRecord

End Sub

 

By default, when you assign a value to an applicationsetting, it is saved automatically when the application is shut down. This canbe verified by viewing the Application tab in the project properties window(see Figure 13).

 


Figure 13: Automatically savingMy.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:

 

My.Settings.Save()

 

But where are the values of the application settingsstored? For user-scope application settings, the values are stored in theuser.config file (see Figure 14) located in directories deeply nested withinthe C:Documents and SettingsWei-Meng LeeLocal SettingsApplication Datafolder. For application-scope application settings, they are stored in theapp.config file usually deployed together with the application.

 

          type="System.Configuration.UserSettingsGroup, System,            Version=2.0.0.0, Culture=neutral,            PublicKeyToken=b77a5c561934e089" >                type="System.Configuration.ClientSettingsSection,          System,Version=2.0.0.0, Culture=neutral,          PublicKeyToken=b77a5c561934e089"          allowExeDefinition="MachineToLocalUser"          requirePermission="false" />                          6             Figure 14: Thecontents of the user.config file for our application.  Application Events One very useful new feature in Windows Forms 2.0 is theapplication events handlers. To view all the application events, click the ViewApplication Events button on the Application tab (see Figure 15).  
Figure 15: Viewing the applicationevents.   The ApplicationEvents.vb file contains the code forservicing the various events in the application. The following events aresupported: 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 theapplication 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 eventsfrom the drop-down list located at the top of the window (see Figure 16). As anexample, if you want to ensure that only one instance of your application canrun at any one time, select the StartupNextInstance event.  
Figure 16: Setting the applicationevents to service.   Also check the Make single instance application checkbox,as shown in Figure 15. This will ensure that when another instance of theapplication is executed, the StartupNextInstance event will be fired. Thisevent is useful for cases where you want to allow a single instance of yourapplication to run on a client s machine.   Code the StartupNextInstance event handler as follows:  Private Sub MyApplication_StartupNextInstance( _ ByVal sender As Object, _ ByVal e AsMicrosoft.VisualBasic.ApplicationServices. _ StartupNextInstanceEventArgs) Handles Me.StartupNextInstance  MsgBox("Anotherinstance of the application is " & _  " already running.Application will now exit.") End Sub   When you try to run more than one instance of theapplication, the message box shown in Figure 17 will appear.  
Figure 17: Displaying the errormessage when trying to start another instance of an application.  Conclusion In this article, you have seen some of the newproductivity features of Windows Forms 2.0. In particular, you have seen howthe visual designer uses Snaplines to help you position your controls. You havealso learned how to use the data-binding capabilities of Windows Forms 2.0 todisplay records on your form without writing a single line of code. Last butnot least, the Application Settings feature allows you to persist applicationstate easily by providing all the plumbing code needed. As you can see, allthese new features save you lots of effort in writing code usually required formundane tasks, freeing you to spend more time to add features to your application.   In PartII we ll look at the new deployment technology known as ClickOnce, as wellas discuss a new feature known as RegFree COM and how it can be used togetherwith ClickOnce to simplify your deployment tasks. We ll wrap things up with alook at some new and improved Windows controls and how you can use them tocreate professional Office-like applications.  Wei-Meng Lee (http://weimenglee.blogspot.com)is a technologist and founder of Developer Learning Solutions, a technologycompany specializing in hands-on training on the latest Microsoft technologies.Wei-Meng speaks regularly at international conferences and has authored andcoauthored 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 ReillyMedia, Inc.).      

Read more about:

Microsoft
Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like