Share via


[Editor's Update - 1/20/2006: This article refers to a beta version of Visual Studio 2005. An updated version of the article, reflecting features found in the final release of Visual Studio 2005, can be found at Smart Clients: Craft A Rich UI For Your .NET App With Enhanced Windows Forms Support.]

.NET Framework 2.0

Craft a Rich UI for Your .NET App with Enhanced Windows Forms Support

Michael Weinhardt and Chris Sells

This article was based on a pre-release version of Microsoft Visual Studio 2005, formerly code-named "Whidbey." All information contained herein is subject to change.

This article discusses:

  • What's new in Windows Forms controls
  • Working with themes
  • Binding and displaying data
  • Other data-specific features
This article uses the following technologies:
C# and Windows Forms

Contents

System.Windows.Forms
Windows Themes Support
Control Layout and Configuration
Controls and Data Binding
The GridView
Typed DataSets
DefaultInstance
DataContainer Control
Master-detail Binding
ClickOnce Deployment
Configuring ClickOnce Deployment
Deployment
ClickOnce Versioning and Rollback
Conclusion

Microsoft really hit a sweet spot with the .NET Framework 1.0. Not only did .NET signify a fundamental shift in the way developers build and distribute Windows®-based applications, but it also created a great technological platform for scaling features upwards and outwards. Visual Studio® 2005 is a very solid case in point and does both exceptionally well with a smorgasbord of new and improved functionality. The scope of these changes most definitely covers the Windows Forms subset of the Microsoft® .NET Framework, starting with the core System.Windows.Forms and reaching out across a wide variety of supporting technologies, both old and new alike, including ADO.NET, ObjectSpaces, and ClickOnce deployment.

Productivity improvements are found in every nook and cranny of Visual Studio 2005. They include IDE enhancements, improved control and data designers, and code generation. Code junkies may be disheartened by how much less code needs to be written for a variety of scenarios, while the rest of us will have more time for Battlestar Galactica reruns.

System.Windows.Forms

Significant work has gone into System.Windows.Forms, the beating heart of the technologies that comprise Windows Forms. At the time of this writing, the namespace's usable surface areas, consisting of public types and members, has increased by 67 percent and 127 percent respectively, indicating that Visual Studio 2005 is most definitely a major release. While we simply don't have enough space in this article to cover everything, Figure 1 gives you an overview of the major new areas of improvement with additions and enhancements covering a wide range of areas, such as better theme support, improved data binding, and the GridView control.

Figure 1 New Windows Forms Features

Category Description
Layout controls SplitContainer, FlowLayout, and TableLayout container controls for managing controls at design time and run time.
Data binding controls GridView control for enhanced tabular data presentation, navigation, and processing. DataContainer control for simplifying data binding, data-bound UI design, native VCR-style UI support, and master-detail UI support.
UI building blocks MainMenu component now supports menu item images. WinBar control implements a fully-featured tool strip like you find in Microsoft Office. WebBrowser control is a managed Web browser wrapper over shdocvw.dll.
Control and component ControlArray makes a comeback to provide a single interface
management for managing multiple controls, not necessarily of the same type. ComponentArray is a component-oriented alternative to the ControlArray.
Asynchronous call support BackgroundWorker component wraps worker-thread creation and management (technically not from System.Windows.Forms, but certainly a Windows Forms must). Sound file loading in the sound component. Image file loading in the PictureBox control.
General improvements Autocompletion support for the TextBox and ComboBox controls from a variety of system sources including Internet Explorer history and Start | Run. Most recently used List item formatting support for the ComboBox and ListBox controls.

Windows Themes Support

While creating a new Windows Forms project is the same as it has always been, the result gives rise to one of the first changes you may notice: default support for Windows themes. A Windows theme is a shell-wide user setting that dictates the look of the Windows UI. It can be specified by right-clicking on the desktop and then clicking Properties | Themes from the Display Properties dialog box.

Because Windows themes are user-specified, it is the duty of Windows Forms apps to reflect them. Themes are supported in existing versions of .NET, but version 1.0 of the .NET Framework requires the developer to add a specially named manifest file to a particular location in the file system. The .NET Framework version 1.1 simplifies the process by providing the Application.EnableVisualStyles method to enable support, and by setting the FlatStyle property to "System" on each control that implemented the method. Visual Studio 2005 further improves the process by including the call to EnableVisualStyles by default in a new Windows Forms project's default form:

public class Form1 : System.Windows.Forms.Form { ••• [STAThread] static void Main() { Application.EnableVisualStyles(); Application.Run(new Form1()); } ••• }

Traditionally, setting a control's FlatStyle to System indicates that the operating system dictates how a control will look when rendered. Now, a majority of Visual Studio 2005 controls render according to the Windows theme presently in use when FlatStyle is set to the default value of "Standard." This is semantically equivalent to a System setting and consequently saves you the effort of setting it in the designer. Whether the FlatStyle is Standard or System, the benefit for developers is theme sensitivity, including support for dynamically responding to a theme change at run time without requiring a single line of code.

Control Layout and Configuration

Windows themes support requires no effort beyond creating a project or form and dragging the necessary controls onto it. However, laying controls out on a form and configuring them can be a time-consuming process, especially for complex forms. In order to make this task easier, the Windows Forms designer comes with several new features that are intended to curtail design-time chores, including Snap-To Alignment, Edit Properties Mode, and smart tags, which are accessible in situ with the control.

While you can still use the Visual Studio Layout toolbar to align controls horizontally and vertically, you can only do so once the controls are on the form. Alternatively, you can use Snap-To Alignment to achieve the same effect as you drop controls onto a form and drag them around, avoiding the Layout toolbar and associated design-time expense, including control selection and toolbar button clicking. Snap-To Alignment is manifested as one or more sticky blue lines that guide controls into alignment with other controls in close proximity.

Figure 2 Edit Properties

Figure 2** Edit Properties  **

Another new feature, Edit Properties Mode, allows you to tab through controls and change their properties directly on the page. Edit Properties Mode is initiated by selecting it from any context menu on the Windows Forms designer or by clicking the menu item of the same name. The next step is to select and tab through each property, editing as you go. The process is illustrated in Figure 2. When finished, return to normal editing by clicking "Return to Layout Mode." Setting a property is a simple way to alter a control. Completely replacing one control with another more relevant control is not as simple; you will need to delete an existing control, drop a new one on the form, and reconfigure it. Complex multistep designer tasks like this are the perfect use for smart tags, which are design-time tasks packaged into a single step exposed as a menu item icon near the related control. Smart tags also expose simple, although frequently performed, design-time tasks, including setting a TextBox's Text property the moment it's dropped onto a form.

Controls and Data Binding

In addition to the IDE improvements, Windows Forms in Visual Studio 2005 offers new controls as well as improvements to old favorites such as the TextBox and ComboBox. As an example of some of the new and improved controls in use, Figure 3 shows the UberBrowser, built using much less code than would have been required in previous versions of Windows Forms.

Figure 3 Web Browser Using New Controls

Figure 3** Web Browser Using New Controls **

This simple example demonstrates how the enhanced toolbox in Visual Studio 2005 allows you to build more with less. For example, the fully-functional UberBrowser took about 10 minutes to design and required only 85 lines of code to hook up the traditional gamut of Web navigation events and to implement URL navigation history. The actual work of Web navigation and HTML rendering is performed by the WebBrowser control in the right pane. The splitter bar and right and left panes are provided by a single SplitContainer.

The ComboBox, as shown in Figure 3, sports new autocompletion support. Autocompletion is implemented across three properties, starting with AutoCompleteMode, which allows you to set the autocompletion style from an enumeration of the same name:

enum AutoCompleteMode { None = 0x0, // No autocompletion AutoSuggest = 0x1, // Possible matches chosen from drop-down list AutoAppend = 0x2, // Possible matches // appended to text // while typing AutoSuggestAppend = 0x3 // AutoSuggest and // AutoAppend combined }

An option other than "None" requires you to set the AutoCompleteSource property to one of several system autocompletion sources that have been specified by the AutoCompleteSource enumeration:

enum AutoCompleteSource { FileSystem = 0x1, // File system HistoryList = 0x2, // All URLs from History list RecentlyUsedList = 0x4, // All URLs from Recently Used list AllURL = 0x6, // HistoryList + RecentlyUsedList AllSystemSources = 0x7, // FileSystem + AllURL CustomSource = 0x40, // AutoCompleteCustomSource None = 0x80 // No source }

CustomSource instructs the ComboBox that you will provide autocompletion options from a collection of items stored in the AutoCompleteCustomSource property. Currently, the ComboBox and TextBox are the only controls that offer autocompletion.

The GridView

Most controls in the Toolbox support data binding to an arbitrary data source through a native data-binding infrastructure. In a variety of scenarios, particularly prototyping and RAD development, data binding is critical. The Windows Forms team has dramatically enhanced the data-binding space with improvements to typed DataSets, new controls including the GridView and the DataContainer, and richer design-time support for speedier development. These features allow you to build either a field-style or tabular-style UI with equal ease.

Sometimes a tabular-style UI is the most appropriate for presenting and processing bound data and, to that end, Microsoft included the DataGrid control in previous versions of the .NET Framework. For Visual Studio 2005, the Windows Forms team responded to community feedback on the DataGrid and decided to construct a new grid control, System.Windows.Forms.GridView (see Figure 4).

Figure 4 GridView Columns

Possibly the most striking difference between the DataGrid and GridView is the GridView object model, which has been abstracted into a natural grid structure built upon columns, rows, and cells that allow developers to logically drill down through tons of intuitively located functionality, including:

  • Rich UI customization support through styles, formatting, layout, and item selection
  • The ability to natively display a broader variety of data than the DataGrid allowed, through a richer set of column types, including images
  • Nifty features like frozen columns (as in Microsoft Excel) and run-time column reordering (as in Microsoft Outlook®)
  • More than 100 events for granular control over navigation, editing, validation, custom painting, and error handling

In combination with a comprehensive design-time experience, the rich feature set supports rapid customization with less reliance on code—in some cases due to the folding of common DataGrid coding scenarios into native GridView methods, properties, and events. One such example is row selection on cell click, which is now exposed by the GridView as the SelectionMode property. Of course, no control can be everything to everyone. When they fall short, developers lean on extensibility to incorporate custom features. The GridView infrastructure doesn't disappoint with a variety of cell, row, and column base implementations you can derive from and plug into. The overall result for the GridView is a much more compelling grid-style control than the DataGrid.

Typed DataSets

The GridView control is part of a family of controls that can bind to data sources such as arrays, collections, and typed DataSets. The advantage of typed DataSets is that the .NET Framework plumbing allows controls to bind within the designer to help developers visualize the UI at design time. The GridView supports this by autogenerating a column for each field on the data source at design time. Visual Studio 2005 enhances typed DataSets to make your life simpler. You will spend less time in the designer as typed DataSets now fully decipher data source metadata, including foreign-key constraints and autoincrement seeds and steps, as shown in Figure 5.

Figure 5 Default Typed DataSet

Figure 5** Default Typed DataSet **

The designer also generates a Fill query, which wraps the table's SELECT statement and is implemented as a method of the same name on the typed DataSet. Sometimes, the SELECT, INSERT, UPDATE, and DELETE statements you specify initially are not useful in all situations. For example, the Fill method will return all Employees, although there are times when you may only need to return a single employee. In this particular situation, it makes sense for you to use the same table and fill it with a more specific query. The typed DataSet designer accommodates by allowing you to add your own queries from the appropriate table's context menu by selecting Add | Query from the table's context menu.

The "DbTable Query Wizard" dialog opens to help you construct your query, after which the table is updated with the new data. When you complete the configuration of a typed DataSet, you typically bind it to one or more controls in the user interface. In Visual Studio 2005, typed DataSets can be bound directly to controls that implement DataSource and DataMember properties without the need for adding a DataSet to the form.

DefaultInstance

Anyone who has made heavy use of typed DataSets knows that, in general, each new typed DataSet class is used in one place in an application. Because the Windows Forms team knows this and wants to make our lives easier, they've put a static property, called DefaultInstance, into each generated typed DataSet class to hold that single instance. It's implemented like so:

public static EmployeeTDS DefaultInstance { get { if (_defaultInstance == null) { _defaultInstance = new Northwind(); } return _defaultInstance; } }

You use the DefaultInstance property this way:

public class Form1 : System.Windows.Forms.Form { ••• private void Form1_Load( object sender, System.EventArgs e) { // Load data EmployeeTDS.DefaultInstance.LoadData(); } ••• }

Databound controls set their DataSource property with the default instance's type name that by default is ProjectNamespace.TypedDataSetName, while the subsequent process of specifying a DataMember remains unchanged.

DataContainer Control

The GridView control is an example of a complex bound control, which means that it knows how to manage the data binding to support navigation, inserts, updates, and deletes. On the other hand, simple bound controls don't know this and require you to implement equivalent support through the data source's binding manager, typically with a VCR-style user interface. You would use simple bound controls when your preference for presenting list-style data is as a set of fields rather than a grid. This approach requires you to add fields to the form manually as a set of appropriate controls, such as Labels and TextBoxes, resulting in something that looks like Figure 6.

Figure 6 Basic UI

Figure 6** Basic UI **

While you can implement such Details Forms by hand, in Visual Studio 2005 you can implement them in one fell swoop with a DataContainer bound to a typed DataSet. Simply select the Details Form menu item from the DataContainer's smart tag.

This feature will automatically generate all the fields from the selected data source for you. In addition, the DataContainer will load and save the data and adds VCR-style navigation and editing by default, without writing code. The result is shown in Figure 7.

Figure 7 Field-style UI with VCR Controls

Figure 7** Field-style UI with VCR Controls **

If your UI requirements change and a tabular-style UI is more suitable, you can use the DataContainer to do the hard work of changing the UI for you by selecting the appropriate option from the DataContainer's smart tag. The designer removes all existing controls and replaces them with a single DataGrid (although in future versions of Visual Studio this will most likely be a GridView).

Master-detail Binding

The multifunctional DataContainer also happens to be a great tool for constructing master-detail UIs, which provide a Forms-based visualization of the one-to-many relationships used in relational databases. One example of this is the Employees-Orders relationship, which is correctly configured for you by simply adding the Orders table to the typed data.

Figure 8 Master-detail Form

Figure 8** Master-detail Form **

Since we already have the master UI generated (shown in Figure 7) all that we need to do is drag a GridView onto the form, set its DataSource to the DataContainer, and its DataMember property to the Orders-OrderDetails relationship—FK_Orders_Employees in this case—resulting in Figure 8.

ClickOnce Deployment

When you finally have all the controls you need on your forms and the code needed to make them work together, you'll have an application that you still need to deploy. Deploying an enterprise-wide Windows Forms application to a user base of any nontrivial size can be quite an installation and versioning challenge, so developers of previous generations have been more than happy to trade rich Windows UIs for Web applications to gain the accompanying deployment benefits.

With .NET, Microsoft began the process of creating an infrastructure that allows Windows Forms applications to be deployed with the same ease as ASP.NET applications. Prior to Visual Studio 2005, the .NET Framework supported no-touch deployment, which allowed Windows Forms applications to be deployed from either a URL or a Universal Naming Convention (UNC) file path and executed within a code access security (CAS) controlled sandbox on the client machine. No-touch deployment has evolved into ClickOnce deployment in Visual Studio 2005, incorporating several new features along the way to offer Windows Forms developers a deployment infrastructure as slick as Web applications. In particular, ClickOnce offers improved support for application delivery, versioning and rollback, greater control over client-side application installation, permission elevation, and design-time configuration support all included in the structure of Visual Studio.

Configuring ClickOnce Deployment

[Editor's Update - 7/1/2004: FTP servers can be used as publishing targets, but they cannot be used as deployment sources (i.e. clients can't install from an FTP server).] ClickOnce deployment allows you to specify which of these your application will be published to and installed from and the mechanism by which it is installed (through a Web page, for example). Installation can also be controlled by configuring whether the application is physically installed to the client machine. If installed to the client, you can then stipulate whether the application checks for updates before it loads or as it runs, how frequently it does so, and enforce required updates—a useful option to deploy critical updates. It is also possible to specify application prerequisites, the most likely being the .NET Framework itself. Several security settings can also be set from the Security property page.

When it comes to publishing, you can build and publish the application in one step by clicking Project | Publish Project, which will both build and publish the application. The process of publishing is managed by the Publishing Wizard, which basically revisits your publishing configuration settings, allowing you to change them on a per-publish basis. The final form in the publishing process presents you with a list that confirms your choices and gives you an option to either publish the application or go back and alter the settings. The Publishing Wizard then enacts your choices and publishes the application as required.

Deployment

[Editor's Update - 7/1/2004: If the online application is running in the sandbox, the user might not be presented with the dialog.] When the download has completed, the actual application will be loaded into and begin executing from AppHost.exe. The application is stored in a local cache unless you specify no client-side installation.
[Editor's Update - 7/1/2004: The application is always cached locally.] While subsequent application invocations will always need .deploy, the application will execute from the local cache until .deploy specifies that a new version is available on the server.
[Editor's Update - 7/1/2004: If the application is not granted the necessary permissions, it won't be downloaded.]

ClickOnce Versioning and Rollback

If requested, an icon is added to the Start menu and an entry is added in Control Panel | Add/Remove Applications. From Add/Remove Applications, you can either completely uninstall the application or revert to the previous version, if there was one. ClickOnce versioning depends on the version numbers you specify for your application using the AssemblyVersionAttribute, which is automatically generated into the AssemblyInfo.cs file of every Windows Forms project by default. It looks like this:

[assembly: AssemblyVersion("1.0.*")]

The version number is used to determine when a new version is ready for download. It is also used to name both the deployment folder and the client-side cache folder in which the application resides. The naming convention for both folders is ApplicationName_major#.minor#.build#.revision#.

ClickOnce deployment is a powerful technology that offers many more benefits than we can describe in this article. However, the key motivation for using ClickOnce is the ease of deployment, installation, and versioning for your Windows Forms applications. For more information on ClickOnce, see the article "ClickOnce: Deploy and Update Your Smart Client Projects Using a Central Server" by Brian Noyes in this issue of MSDN® Magazine.

Conclusion

When you consider the large number of new features in Visual Studio 2005, you'll realize that we have barely begun to discuss the wide variety of technologies that you will likely use in Windows Forms development. These include improvements in ADO.NET and support for an entirely new way to access relational data via object-relational mapping with the brand new ObjectSpaces. What we've done here is give you a taste of the most important new features and explain the corresponding increase in productivity that they facilitate, beginning with IDE and designer improvements in Visual Studio and moving on to controls that are either improved from previous versions, like the TextBox and the ComboBox, or just plain new, like the GridView and the WinBar. The GridView and DataContainer controls, in conjunction with typed DataSet enhancements, will help you incorporate richer data presentation and processing into your applications more rapidly.

Finally, ClickOnce deployment simplifies the entire Windows Forms deployment process while providing deployment capabilities comparable to traditional installers.

Michael Weinhardt is currently co-updating Chris Sells's book, Windows Forms Programming in C# and writes a monthly column for MSDN Online called "Wonders of Windows Forms."

Chris Sells is a Content Strategist for MSDN online, currently focused on "Longhorn," the next version of Windows. More information about Chris and his various projects is available at https://www.sellsbrothers.com.