asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search










Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

Windows Forms Object Data Binding in .NET 2.0 -- Cont'd
By Rockford Lhotka


  • email this article to a colleague
  • suggest an article

    Data Binding a Form to an Object

    Before dragging an entire class from the Data Sources window onto a form, we can choose how the class will be rendered into controls. As shown in Figure 5, the two primary options are to display the data in a DataGridView control (which is the new data bound grid control in Windows Forms), or in a details view.


    Figure 5. Options for rendering a class as controls on a form.

    If we choose the details view, a control will be created for each property. The type of control is typically a TextBox, though we can override that by using a drop-down menu attached to each individual property in the Data Sources window.

    Once we've set up our data source to render with the details view, we can simply drag the class onto a form to get a display. Not only does this create individual controls for each property, but it also creates label controls and lines them all up nicely. Additionally, a DataNavigator control is created on the form. The DataNavigator control is a special toolbar that provides VCR-style controls for data navigation. The result is shown in Figure 6.


    Figure 6. Result of dragging an object data source onto a form.

    Also note that two non-visual controls are created. These are the ProductDataConnector and ProductDataNavigator components.

    The ProductDataConnector is the object that manages data binding between the controls on the form and the Product object to which the form is bound. The data connector concept is new in Windows Forms and basically replaces the binding context concept from .NET 1.x. Many people found the binding context and currency manager implementations quite difficult to work with in .NET 1.x, and so they've been replaced with this new data connector concept.

    The ProductDataConnector provides strongly typed access to the data source. This is used by any data bound controls on the form and should also be used by any code we write on the form. The goal is that no code in a form will ever directly interact with a data source, but rather will always go through a data connector. This provides a very powerful level of abstraction between the UI and the underlying data source.

    The ProductDataNavigator is entirely optional, and is quite configurable. Data navigator controls rely on the data connector to interact with the data source, just like all other controls, so the overall model is preserved. If you prefer a VCR-style interface, it is largely pre-build for you. The thing to remember about the data navigator is that you can customize or remove it without fear of breaking anything. Just deleting the control from the form is perfectly acceptable. Likewise, you can remove or hide individual components on the toolbar part of the control itself. So if you don't like the VCR controls, but do want to keep the Add/Delete/Save elements of the toolbar you can do that.

    For our example here, I'll just remove the control entirely, as it isn't necessary, and I'm not a big fan of VCR-style navigation in any case.

    By removing the control, we're left with the two labels, two textboxes and the ProductDataConnector on the form. Let's look at the NameTextBox control in a bit more detail. Since it was created by dragging and dropping a data source, it is already set up for data binding. We can see the details by looking at the (DataBindings) details in the control's Properties window as shown in Figure 7.


    Figure 7. The data binding properties for NameTextBox.

    We can see here that the Text property of the control is bound to the Name property of the ProductDataConnector. The data connector will, in turn, be connected to our Product object. It is very clear from this diagram, however, that the data connector sits between the UI and the underlying data source.

    The only code we need to write to make this form work is to create a Product object and connect it to the ProductDataConnector. We can do this in the form's Load event. The following is the code listing for the form:

    
    Public Class ProductEdit
    
      Private Sub ProductEdit_Load(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles MyBase.Load
    
        ProductDataConnector.DataSource = _
          Product.NewProduct("Oak 2x4", 3.59)
    
      End Sub
    
    End Class
    
    
    Due to the partial class technology in .NET 2.0, code behind forms is now much simpler than it was in .NET 1.x. There's no more code region for generated code, since that code is now in a separate file that is connected to our code through the partial class concept.

    But in our case, we're interested in the line of code that creates a new Product object and provides it as the data source for the ProductDataConnector object:

    
        ProductDataConnector.DataSource = _
          Product.NewProduct("Oak 2x4", 3.59)
    
    
    The result of this one line of code is that the form's controls are now bound to the Product object. If we run the application, we'll get a display similar to Figure 8.


    Figure 8. Example of running the ProductEdit form.

    As we tab off each field, the data value is automatically updated into the underlying object. Conversely, any changes to the object's state will be automatically displayed in the controls.

    Data Binding a Form to a Collection

    At this point it should be clear that there's good RAD support for binding a simple object to a form for editing. Of course there's also support for binding a collection of objects to a grid for display or editing.

    Displaying a collection of objects is relatively straightforward. Making the collection of objects editable takes a bit more effort as we write the code in our classes. In either case, the UI is mostly code-free since we can use RAD data binding techniques like we did with the simple object earlier.

    Creating a collection of Product objects is straightforward. In fact it is much easier in .NET 2.0 since we can make use of generic collections. Here's the code:

    
    Imports System.ComponentModel.Collections.Generic
    
    Public Class ProductList
      Inherits BindingList(Of Product)
    
      Protected Overrides Function AddNewCore() As Object
    
        Dim prod As Product = Product.NewProduct("", 0)
        Add(prod)
        Return prod
    
      End Function
    
    End Class
    
    
    The new BindingList(Of T) generic base class handles almost every detail of creating a strongly-typed collection. We provide the type, in this case Product, and the generic base class automatically ensures that we have strongly-typed methods such as Item and Remove.

    The only method for which we need to write code is the AddNewCore method. This method is defined by the base class, and if we want to allow the user to add new items by just navigating to the end of the grid control, we need to override this method. When the user navigates to the last row in a grid control, this method is called to create a new object and add it to the collection. The new object is also returned as the result of the method.

    In order to support in-place editing of child objects, we need the child class to implement System.ComponentModel.IEditableObject. This interface hasn't changed from .NET 1.x, and its implementation is beyond the scope of this article. I discussed implementation of this interface in an MSDN article; Windows Forms Data Binding and Objects (http://msdn.microsoft.com/library/en-us/dnadvnet/html/vbnet02252003.asp).

    The modified Product class that implements the interface is available in Listing 1, and the changes required to ProductList are in Listing 2. The key is that IEditableObject allows simple undo capabilities, so when the user presses Esc in the grid, the object can revert its state to the values the object had before the user started editing that row in the grid. What makes it more complex is when the user presses Esc to cancel the addition of a new object. In that case, the child object is responsible for removing itself from the collection.

    Given the final ProductList and Product classes, we can set up a form with a grid control to view and edit the data. To do this, we'll click the Add New Data Source button in the Data Sources window's toolbar to bring up the wizard. This time we'll select the ProductList class as our data source as shown in Figure 9.


    Figure 9. Selecting the ProductList class as a data source.

    Now the Data Source window displays both the Product and ProductList classes as possible data sources as shown in Figure 10.


    Figure 10. Data Source window displaying both data sources.

    Due to the way this pre-beta version of Visual Studio 2005 works, we can't simply drag the ProductList item onto the form and get a meaningful grid display. That is the design goal, but that particular approach doesn't work in the alpha build I'm using. Instead, we need to drag the Product class onto the form, first making sure to use its drop-down menu to select the DataGridView option. The result is a form with a ProductDataNavigator control (the toolbar for VCR-style navigation) and a DataGridView control. Figure 11 shows the form after I've set the DataGridView to dock to the full form.


    Figure 11. ProductView form with generated controls.

    Notice that the grid columns are set up to match the properties from the Product class. All we need to do now is bind the ProductDataConnector to a ProductList object. Here's the code behind the ProductView form:

    
    Public Class ProductView
    
      Private Sub ProductView_Load( _
        ByVal sender As System.Object, ByVal e As System.EventArgs) _
        Handles MyBase.Load
    
        Dim list As New ProductList
        list.Add(Product.GetProduct("Oak 2x4x8", 3.59))
        list.Add(Product.GetProduct("Pine 2x6x8", 10.29))
        list.Add(Product.GetProduct("1lb 6 penny nails", 14.39))
    
        ProductDataConnector.DataSource = list
    
      End Sub
    
    End Class
    
    
    We create a ProductList object and populate it by creating some Product objects. Notice that we're using the new GetProduct factory method, so the Product objects can differentiate between objects already in the grid and ones added dynamically through the AddNewCore method. Remember that the AddNewCore method uses the NewProduct factory method.

    Then the ProductDataConnector object's DataSource property is set to the new ProductList object. Since the ProductList object contains a list of Product objects, the data connector is able to take the data from the collection and provide it to the grid control appropriately.

    Again, the way this should work is that we'd have a ProductListDataConnector, since we would have dragged the ProductList class directly onto the form to do the binding. In this pre-beta release however, we are using this slight workaround instead.

    The end result is that our form displays a grid with the data. The user can edit the data in each row. Pressing Esc on a row while editing will undo the edits. The user can also remove a row by clicking on the left to highlight the row and pressing the Delete key.

    We can also add new rows by navigating to the last row in the grid as shown in Figure 12.


    Figure 12. Adding a new row to the grid and the underlying collection.

    Navigating to another row will commit the new addition. Pressing Esc, on the other hand, will cause the new row to be removed.

    Finally, note that the data navigation toolbar is functional. Without having to write any code, we've enabled the user to navigate between rows and to add or remove rows by clicking in the toolbar.

    The Save button in the toolbar is disabled. To use it, we'd have to enable it in the form designer and write code behind that button to properly save our object's data to disk.

    << Introduction •       • Conclusion >>

  • Supporting Products/Tools
    Proposion N2N
    Proposion N2N connects Microsoft .NET applications to Lotus Notes and Lotus Domino databases. This ADO.NET managed data provider allows you to perform blindingly fast queries and updates of Notes data from ASP.NET pages, .NET web services, Windows, or Mobile applications. An innovative SQL-like query language leverages the unique features of Notes and makes collaborative software accessible to relational database programmers.
    [Top]
    Other Articles
    Sep 15, 2005 - Building an Image Keyword System
    Unlike text-based file formats image files aren't made up of words, which makes searching for an image file by keyword difficult. Instead of being able to simply open the file to see what it contains, we're stuck looking at the text around it and other metadata to determine the image's meaning. In this article, Ziran Sun shows you how to build a simple database-based image keyword system that allows you to associate keywords with images and use these keywords to make finding images easier.
    [Read This Article]  [Top]
    Apr 7, 2005 - A Step-by-Step Guide To Using MySQL with ASP.NET - Part 2
    In the second part of of his article on using MySQL with ASP.NET, Ziran Sun covers how to add a new MySQL user to the database server, assign the user the appropriate permissions, connect to the database, and build a simple ASP.NET page to perform a query.
    [Read This Article]  [Top]
    Feb 10, 2005 - A Step-by-Step Guide To Using MySQL with ASP.NET - Part 1
    Back in the days of classic ASP, if you were building a database-driven web site, your choice was either to invest a lot of money to get a copy of Microsoft SQL Server (or some other enterprise-ready database) or invest a lot of time finding a way to deal with the performance and scalability limitations of Microsoft Access. Luckily these days there's another viable alternative: MySQL.
    [Read This Article]  [Top]
    Jan 27, 2005 - Moving a Database from SQL Server 7.0 to SQL Server 2000
    Moving or copying a SQL Server database from one machine to another requires a lot of preparation in order to ensure a smooth transfer. In this article, Dina Fleet Berry examines the different methods and highlights the different issues associated with each of them.
    [Read This Article]  [Top]
    Jan 6, 2005 - Debugging a SQL Stored Procedure from inside SQL Server 2000 Query Analyzer
    There are many times when using SQL Server 2000 Query Analyzer to debug SQL statements is a better choice than debugging in Visual Studio .NET. In this article, Dina Fleet Berry explains why and walks you through the debugging process step-by step.
    [Read This Article]  [Top]
    Nov 24, 2004 - Persisting .NET Objects to SQL Server Using SQLXML and Serialization
    As a follow up to his article on retrieving objects from SQL Server using SQLXML and serialization, Gianluca Nuzzo discusses saving objects back to SQL Server using a schema definition file and updategrams.
    [Read This Article]  [Top]
    Sep 14, 2004 - Transaction Processing in ADO.NET 2.0
    One area that stands out when comparing ADO.NET 1.x to ADO.NET 2.0 is transaction processing. Bill Ryan shows just how easy transaction processing has become with the TransactionScope object in ADO.NET 2.0.
    [Read This Article]  [Top]
    Sep 8, 2004 - Custom Object Data Binding with .NET
    Developers often use brute force coding to marshal data between the GUI and application objects. In this article, Luther Stanton explains how to use .NET's out-of-the box data-binding functionality to make this job much easier.
    [Read This Article]  [Top]
    Sep 2, 2004 - Queue MSMQ Messages from SQL Server
    Learn how to create a console application to queue a message in Microsoft Message Queuing (MSMQ) and then use an extended stored procedure to call the console application from a SQL Server trigger.
    [Read This Article]  [Top]
    Aug 30, 2004 - Tuning Up ADO.NET Connection Pooling in ASP.NET Applications
    Connection pooling increases the performance of Web applications by reusing active database connections instead of creating a new connection with every request. This article shows how to monitor the connection pool, diagnose a potential problem, and apply the appropriate fix.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry



    JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers