Devlico.Us
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @devlicious

Derik Whittaker

Thoughts on Software Development, .Net, OOP, Design Patterns and all things cool



Data Binding a Business object to a UI Control (Text Box)

So one of the nice new feature in .net 2.0 is the enhanced support for binding business objects to UI controls.  This is very nice because it will allow you to write a single line of code that allows the business object and the UI control (text box) to exchange data both upstream and downstream.

 
Setting up the binding for the UI control (a text box in this example) is actually pretty easy.  There are a few simple steps needed in order to make this work.

  1. Create a User Control (referred to as MyControl)  that inherits off of your desired Control (ie Text Box)
  2. Add some custom code to your newly created MyControl to setup the binding
  3. Add a single line of code to your application to bind the business object to the UI Control

 
Below is the code needed in MyControl

///
<summary>
/// Sets up the data binding with the control
///
</summary>
///
<param name="bindingDataObject">The data object (business entity) that will be bound to the control</param>
///
<param name="bindingPropertyName">The 'magic string' name of the property to bind the control to.</param>
public
void SetupControlBinding( object bindingDataObject, string bindingPropertyName)
{
    // The property on the control that gets/sets the value to the control

    string controlValuePropertyAccessor = "Text";     
    Binding currentBinding = this.DataBindings[ controlValuePropertyAccessor ];        


    // Whack any bindings that may already exists so we can start with a clean slate
    if ( currentBinding != null ){ this.DataBindings.Remove( currentBinding ); }

        // Get the value out of the binding object and set it to the control
        object bindingObjectValue = GetPropertyValueFromReflection( bindingDataObject, bindingPropertyName );
        SetPropertyValueFromReflection( this, controlValuePropertyAccessor, bindingObjectValue );

        // Create the new bindings and then add them
        Binding binding = new Binding(controlValuePropertyAccessor, bindingDataObject, bindingPropertyName, false, DataSourceUpdateMode.OnPropertyChanged, null, null, null );

        binding.ControlUpdateMode = ControlUpdateMode.OnPropertyChanged;
        this.DataBindings.Add( binding );
}


I have created and used 2 helper methods for the reflection code.  These 2 methods would be best served if they were in a common utilities class, but for this example they are in the UI control.

 

/// <summary>
///
Helper method, should go in its own class for reuse
/// </summary>
private object GetPropertyValueFromReflection( object obj, string propertyName )
{

    object returnValue;
    PropertyInfo propInfo = obj.GetType( ).GetProperty( propertyName );
    returnValue = propInfo.GetValue( obj, null );      

    return returnValue;
}

      
/// <summary>
///
Helper method, should go in its own class for reuse
/// </summary>
private void SetPropertyValueFromReflection( object owningObject, string propertyName, object propertyValue )
{

    PropertyInfo info = owningObject.GetType( ).GetProperty( propertyName );         
    // Need to be carefull of generics, there is added logic needed for handeling these types         

    info.SetValue( owningObject, propertyValue, null );

}

 

 

Now in order to setup the binding between the business object and the MyControl you will only need to call one line of code in your UI layer. 

 

Here is that code

 

// ClassObject is an instance of my business object to bind to
// Value1 is the string name of the property in the business object that
//  the actual binding will attach to.

myTextBox1.SetupControlBinding( ClassObject, "Value1" );

 

Well, that is it.  I have shown you how to setup basic data binding to a business object to your UI control.  This example DOES NOT provided support for nullable types as they are special and in my opinion Microsoft did a bad job of building in support for nullables into the UI layer of .net.

I have attached a sample application so everyone can have a fully working example.

 

 



Comments

Joe Niland said:

This a nice explanation of a cool feature. It appears to be an interesting alternative to the ObjectDataSource. What types of situations have you used it for?

# October 3, 2006 11:24 AM

Derik Whittaker said:

We used this in a WinForms application at one of my last companies.  We subclassed all the different UI controls we needed (text box, combo box, etc) to allow for us to data bind to each.

This allowed us to have a single line of code that did the two way population (object to UI, UI back to object).  

Like i said in the post, Nullables are a pain, but they can be done with some simple overriding.  If you would like, i can post on that.

Thanks for the comment, hopes this provides useful to you at some point in the future.

# October 3, 2006 2:16 PM

Tom van Stiphout said:

Please correct the typo in the title "Data Binding a Buinsess object to a UI Control (Text Box)" so your article will show up better in the search engines.

# April 1, 2008 5:48 PM

Leave a Comment

(required)  
(optional)
(required)  

Enter the numbers above:
Add

About Derik Whittaker

Derik is a .Net Developer/Architect specializing in WinForms working out the northern suburbs of Chicago. He is also believer and advocate for Agile development including SCRUM, TDD, CI, etc.

When Derik is not writing code he can be found spending time with his wife and young son, climbing on his bouldering wall, watching sports (mostly baseball), and generally vegging out. Check out Devlicio.us!

Our Sponsors

Proudly Partnered With


This Blog

Syndication

News