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!

Custom Object Data Binding with .NET
By Luther Stanton
Rating: 4.0 out of 5
Rate this article


  • email this article to a colleague
  • suggest an article

    Table of Contents

    • Page 1
      • Introduction
      • Background
      • Data Binding 101: Brute Force Data Binding

    • Page 2
      • Data Binding 201: One Way Data Binding

    • Page 3
      • Data Binding 301: Graduate Level Data Binding
      • Summary
      • About the Author

    Introduction

  • download source code

    The Data Binding capabilities Microsoft has delivered with the .NET platform can be a powerful developer tool. Boiled down to its most simple definition, Data Binding is the act of linking the properties of an application element to specific elements in a graphical presentation element of the application. An example would be linking a property of a custom object, such as the first name on an employee object, to a text box's text property on a windows form.

    Data binding is not a new concept for developers. It has been an essential part of any application; it is the most basic way to move information between an application's end users and the processing logic. Many times this has been done by brute force, manually writing code to move values between properties on objects and GUI elements such as text boxes, data grids, and check boxes. What is new, however, is that the .NET Framework provides a rich set of functionality out of the box. Specifically, the framework provides a great deal of motivation to start using data binding within applications:

    • A "set and forget" approach to maintaining synchronization between GUI controls and object properties
    • Built in type conversion, such as mapping a decimal type property on an object to the "text" string type property on a text box
    • A built in system based on delegates and events to "watch" objects for property changes
    • Building of rich UI experiences by allowing objects to manage the GUI control properties with minimal developer interaction- such as not enabling a save button until values are changed
    • A rich set of events to allow developers to override the default parsing and formatting of values into the assigned control properties
    • Built in data type validation of controls, such as ensuring only valid dates are entered in a text box tied to a date time property on an object.

    In my experiences, the built-in data binding functionality has not been utilized to its fullest potential. I still see a lot of clients continuing to write large amounts of code to marshal data between the GUI and application objects. Perhaps it is lack of realization of what .NET has to offer or a lack of understanding of how.NET manages data binding behind the scenes. It is my hope to eliminate both of these hurdles with this article and begin to open up the possibilities of data binding to your applications.

    I would like to set some boundaries up front of what will and will not be covered in this particular article, as data binding is a broad subject. This article only focuses on using data binding with custom single instance objects binding to Windows Forms controls. I will not be focusing on Web Form binding, nor will I be focusing on the binding of custom collections to elements such as data grids and drop down boxes. I realize that a large amount of development around ASP.NET Web Forms is being completed; however, I chose to focus on windows forms in order to help prepare you for Smart Client development which is very quickly gaining attention and favor in .NET shops.

    Background

    Throughout the discussions and code samples within this article, I use the same class and Windows Form. My goal was to make the sample code simple so as to not cloud the discussions with unnecessary detail, yet be complicated enough to be of interest. With that, I have chosen a single class, an Employee, and a corresponding form to display the properties of that object in a read - write fashion.

    The class I chose for this article is representative of a typical business entity. As such, you will not see any complicated business logic or data access which would reside in other classes in other tiers. When properties need to be populated on the object for purposes of this discussion, I do this manually with hard coded values. When the object needs to be saved, I perform a simple serialization to a file. Again, this is all done to simplify the examples in order to focus on data binding.

    The UML representation of the Employee class is shown in Figure 1.


    Figure 1

    If you wish to view the entire source for the class, please follow the download links at the beginning of this article. There are three solutions included in the download; each corresponds to the various approaches of data binding discussed in the remainder of this article.

    There are a few areas of the code to discuss before moving on to data binding. The first is the "dirty flag" and its implementation. The dirty flag indicates if any properties on the object have been changed to a different value. When ever a property on the object is set, a call to the private CheckDirty function is made, as in Figure 2.


    Figure 2

    The property is not set to the new value unless the call to CheckDirty determines the current value of the property is different from the proposed value.

    The logic of CheckDirty appears in Figure 3. In the subsequent "Data Binding 301" section of this article, you will make use of the dirty flag to enhance the UI experience.


    Figure 3

    The form that will be used throughout the article appears in Figure 4.


    Figure 4

    The form consists of text boxes to display values such as the first and last name of the employee as well as the salary and hire date. I selected different data types, such as decimals and DateTime so that you can examine how data binding within the Framework handles casts and conversions. I also included a check box for the Boolean isActive property and two buttons, "Save" and "Load New Values".

    Now that I have set forth the ground work of what the application elements that you will be working with look like, you will start looking at how data binding works.

    Data Binding 101: Brute Force Data Binding

    The first method of data binding you will look at is what I term the "Brute Force" method. This method has the developer writing all the plumbing between the object and the display and does not rely on any of the Framework's data binding capabilities. I include this to set a base line and to highlight how much .NET actually does for us. All of the code for this example resides in the "ManualDataBindingSolution" available from through the link to the code at the beginning of the article

    Within the form, I have created a member variable to hold the instance of the Employee class that will be used by the form, as shown in Figure 5.


    Figure 5

    Within the form's constructor, the employee object is instantiated and populated as shown in Figure 6. For purposes of illustration I am hard coding values. In a production application, this would most likely be populated through business logic / data classes.


    Figure 6

    On the form's Load event handler, the form's values are marshaled to the form as shown in Figure 7. I call a private method LoadValuesToForm that encapsulates all the manual data binding code, shown in Figure 8. I prefer to place this in a separate method for two reasons: for code reuse by other areas of the form and to keep as much processing logic out of the form event handlers as possible. I feel this leads to a cleaner implementation that is easier to maintain.


    Figure 7


    Figure 8

    As you can see in the code listing, the decimal and DateTime type fields require manual formatting.

    Now that you understand how the object's values are populated and the path the values take to get from the object to the controls on the form, it's time to look at how the values are marshaled from the form's controls to the object such as when the Save button is clicked. The actual logic to marshal the values from the form to the object is shown in Figure 9.


    Figure 9

    Again, it is up to you to add the casts to move data from text based properties to decimal and DateTime type values. Note that in a production application, you may add additional logic to check the values in line 238 - 241 (marshaling the decimal and DateTime values respectively) in order to provide a more descriptive error message. As an example, as the code currently stands, entering a non string date in the Hire Date text box generates the error dialog shown in Figure 10.


    Figure 10

    If all the values are successfully marshaled from the form to the object and at least one property value is changed, the object serializes itself into an XML file in the current application directory.

    The "Load New Values" button simulates reloading the current Employee object with different values, such as loading new values from a data source, etc. Notice that as the properties of the object changes, you still have to manually move the values from the object to the form by calling LoadValuesToForm method. Wouldn't it be nice if the developer did not need to manually track object properties changes, and somehow that update to the form happened automatically as properties change? That is, in fact, one facet .NET Framework data binding provides.

    Data Binding 201: One Way Data Binding >>

  • Rate This Article
    Not HelpfulMost Helpful
    1 2 3 4 5
    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 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]
    Jul 13, 2004 - Retrieving Objects from SQL Server Using SQLXML and Serialization
    This article will describe how to design a data access layer for a set of entities. You'll learn how to write an XSD schema and design two simple helper classes -- one for reading an XML stream from SQL Server using SQLXML and another for deserializing the XML stream.
    [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