Derik Whittaker

Syndication

News


Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
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.

 

 


Posted 10-02-2006 6:33 AM by Derik Whittaker
Filed under: , ,

[Advertisement]

Comments

Joe Niland wrote re: Data Binding a Buinsess object to a UI Control (Text Box)
on 10-03-2006 11:24 AM

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?

Derik Whittaker wrote re: Data Binding a Buinsess object to a UI Control (Text Box)
on 10-03-2006 2:16 PM

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.

Tom van Stiphout wrote re: Data Binding a Buinsess object to a UI Control (Text Box)
on 04-01-2008 5:48 PM

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.

John Pluchino wrote re: Data Binding a Business object to a UI Control (Text Box)
on 05-18-2009 3:43 PM

I am developing a website in Visual Web Developer using ASP.NET and Visual Basic.  I want to bind data from an Object Data Source to a Textbox Control and cannot figure out how to do this.  Could you provide me with a simplified description using Visual Basic?  These are the components I have coded so far but the Parameter "CompanyID" is not being passed to the Sql Server Store Procedure.

The .aspx.vb code...

Protected Sub DropDownListCompany_SelectedIndexChanged(...

       Dim Company As New clsNameAndAddress

       Company = clsCompanyDB.GetCompanyByID(CInt(Me.DropDownListCompany.SelectedValue))

       Me.txtCompanyName.Text = Company.Name.ToString

The Class in the Database Layer...

Public Shared Function GetCompanyByID(ByVal CompanyID As Integer) As clsNameAndAddress

The Stored Procedure...

ALTER PROCEDURE [dbo].[spGetCompanyByID]

(@CompanyID INT)

AS

BEGIN

SET NOCOUNT ON;

SELECT *

FROM tblCompany

WHERE CompanyID = @CompanyID

END

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)