Click here to Skip to main content
Click here to Skip to main content

Data binding concepts in .NET windows forms

, 15 Feb 2003
Rate this:
Please Sign up or sign in to vote.
A detailed look at the concepts involved in data binding and controlling data binding.

Introduction

This article gives an overview of data binding in the .NET framework. Microsoft has beefed up the data binding features considerably in .NET which has made data binding a compelling option to tie your front-end to data sources. I have concentrated on .NET windows forms data binding. 

What is DataBinding?

DataBinding is a powerful feature provided by the .NET framework that enables visual elements in a client to connect to a datasource such as DataSets, DataViews, Arrays etc. Some of the visual elements in the client can be TextBox, Datagrid etc. A two-way connection is established such that any changes made to the datasource are reflected immediately in the visual element and vice versa.

Below is a graphical description of the concept of databinding:



DataBinding Before .NET

In the earlier databinding models, the datasource that could be used was usually limited to a database. All DBMS systems provided their own API's to help in building GUI applications and quickly bind them to the data. Programmer did not have the flexibility to control the databinding process with the result that most developers avoided the use of databinding.

DataBinding with .NET

The .NET framework provides a very flexible and powerful approach to databinding and allows the programmer to have a fine control over the steps involved in the whole process. One of the biggest improvements with .Net has been the introduction of databinding to web pages through the use of .Net server-side web controls. Hence, building data driven web applications has been greatly simplified. Please note that this article only deals with data binding in .NET windows forms.

Advantages of DataBinding

  1. Databinding in .NET can be used to write data driven applications quickly. .NET data binding allows you to write less code with fast execution but still get the work done in the best way. 
  2. .NET automatically writes a lot of databinding code for you in the background (you can see it in "Windows Generated Code" section), so the developer does not have to spend time writing code for basic databinding, but still has the flexibility of modifying any code that he would like to. We get the benefits of bound as well as unbound approach. 
  3. Control over the Databinding process by using events. This is discussed in more detail later in the article.

Disadvantages of DataBinding

  1. More optimized code can be written by using the unbound or traditional methods. 
  2. Complete flexibility can only be achieved by using the unbound approach.

Databinding Concepts

For databinding to take place data provider and a data consumer should exist so that a synchronized link is established between the two. Data providers contain the data and the data consumers use the data exposed by the data providers and display them. 

.NET has expanded the scope of possible data providers. In .NET any class or component that implements the IList interface is a valid DataSource. If a component implements the IList interface then it is transformed into an index based collection. 

Some of the classes that support the IList interface in the NET framework are given below. Please note that any class that implements the IList interface is a valid data provider.

  1. Arrays
  2. DataColumn
  3. DataTable
  4. DataView
  5. DataSet

Please note that IList interface only allows you to bind at run time. If you want to support DataBinding at design time you will have to implement the IComponent interface as well. Also note that you cannot bind to DataReaders in windows forms (you can in web forms).

The .NET framework supports simple and complex DataBinding. Simple databinding is supported by controls like TextBoxes. In Simple databinding, only one data value can be displayed by the control at a time. In complex databinding, which is supported by controls like the DataGrid, more than one data value from the DataSource can be displayed.

Dataflow during DataBinding

A good understanding of the dataflow from the control to the datasource is very important. The diagram below gives an overview of the dataflow and the objects involved.



In .NET, controls can have many properties that can be bound to a DataSource. Each databound property has an associated Binding object. Since a control can have many Binding objects, the control has a collection (instance of ControlBindingsCollection class) of all the Binding objects. Also remember that different properties of the same control can be bound to different datasource's.

Each Binding object talks to a CurrencyManager or a PropertyManager. CurrencyManager and PropertyManager classes merit a little explanation, as they are important. CurrencyManager and PropertyManager are derived from the base class BindingManagerBase. The purpose of BindingManagerBase class is to maintain the concurrency between the datasource and the control. Of the two classes, the CurrencyManager is used when the datasource implements the IList Interface. Examples of such datasources are DataView, DataSet, ArrayList etc. The CurrencyManager can be used for simple as well as complex databinding. However, the PropertyManager is used when the datasource is an instance of a user-defined class. The Control's property is bound to the property exposed by this object. PropertyManager can only be used for simple databinding.

As a rule of thumb if you want your class to be a datasource, you should use CurrencyManager when your class is a data container. However, if you are interested in binding a control to properties exposed by your own class, then using a PropertyManager is easier, since you do not have to implement the IList Interface.

Since a form can contain many controls each binding to a different datasource, a class is needed to manage the CurrencyManager and PropertyManager objects. Therefore, each windows form in .NET has a default BindingContext object associated with it. But, you can always create more BindingContext objects on the form. The BindingContext object is a collection of CurrencyManager and PropertyManager objects.

To summarize:

  • A control can have many properties that can be bound.
  • Each databound property of the control has an associated Binding object.
  • All Binding objects for a control are contained by the control's DataBindings property, which is an instance of ControlBindingsCollection class.
  • Each databinding object talks to a CurrencyManager or PropertyManager object.
  • CurrencyManager and PropertyManager are derived from the BindingManagerBase class.
  • The BindingContext object is a collection of CurrencyManager and PropertyManager objects.
  • By default a form contains one BindingContext object. More BindingManagerBase objects can be created and added to the BindingContext collection.
  • Each CurrencyManager or PropertyManager encapsulates the data access to one datasource per BindingContext object.

Controlling DataBinding

The real flexibility and power of databinding in .NET is realized because the Binding and BindingManagerBase classes supports events. This enables us to change the data passed between the Control and the datasource.

A quick look at the figure below can help you understand this behaviour.



The diagram above depicts how .NET windows forms databinding has been made flexible by making use of the events generated by Binding and BindingManagerBase classes.

The Binding object exposes two events: Format and Parse. The Format event is triggered twice. First when the data is pushed from the datasource to the control and the second time when the datasource is changed and data is updated to the control. The parse event is triggered once when the data is pulled from the control to the datasource.

The Currency Manager (derived from the BindingMangerBase class) exposes three events: CurrentChanged, PositionChanged and ItemChanged. CurrentChanged is triggered when the bound value changes; PositionChanged is triggered when the position property has changed and ItemChanged is triggered when the current item has changed. Please note that the PropertyManager class supports only 2 events: CurrentChanged, PositionChanged.

These events enable a user to have fine control over the dataflow from the control to the datasource and vice versa.

I would like to give an example that will help you in understanding the events of the Binding class. This problem was actually the reason why I got interested in learning about the intricacies of databinding and hence the motivation for this article. The problem came when I was trying to bind a datetime field from SqlServer with a text property of the textbox control. Since, SqlServer stores stores the date in "MM/dd/yyyy hh:mm:ss" format, so the textbox would display the time along with the date. No matter how much I tried to remove the time portion in the display, I could not. Then, I came across the events of the Binding class and the solution using events was very easy and elegant.

'The binding object must be declared with the keyword "WithEvents" in order <BR>'for us to be able to use the format and parse events.
Dim WithEvents oBinding As Binding

Private Sub Form2_Load(ByVal sender As Object, ByVal e As System.EventArgs) _<BR>            Handles MyBase.Load <BR>    'A new binding object declared above using "WithEvents" is explicitly <BR>    'created that binds the text field to the "GetDateTime" property of the <BR>    'MyDateTime class.  The binding object is then added to the textbox's <BR>    'databindings collection.
     oBinding = New Binding("Text", oDt, "GetDateTime")
     txt1.DataBindings.Add(oBinding)


     'Here, the binding object is not explicitly created and hence
     'no events will triggered and the datetime is displayed in <BR>     ' "MM/dd/yyyy hh:mm:ss"
     'format only.
        txt2.DataBindings.Add("Text", oDt, "GetDateTime")
    End Sub

    'This event is triggered right before the txt1's text field displays the <BR>    'datetime value that itobtains from oDt object (the datasource). Here, we<BR>    'have changed the format of display to "MM/dd/yy" although the actual <BR>    'data pulled from oDt is in "MM/dd/yyyy hh:mm:ss" format.
    Private Sub oBinding_Format(ByVal sender As Object, ByVal e <BR>            As System.Windows.Forms.ConvertEventArgs) Handles oBinding.Format
        e.Value = Format(e.Value, "MM/dd/yy")
    End Sub

In the example, there are two textboxes. One is implicitly bound to the datetime property of an object of my custom class and the other is explicitly bound using a binding object which is declared with "WithEvents" keyword so that we can handle the events generated during binding and hence control the display of the data. Also the sample code provides a good example of how to bind your own classes to controls.

The reason I used my own class as a datasource is to avoid the dependency on a SQL Server Database datetime column and therefore make the example self contained. However, the same code can be applied to format the data when the datasource is populated from Sql Server database. Please refer to the sample code for better understanding of how to use events.

Change Log

  1. Added a new C# sample which does the same thing as the VB.NET example.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Tarun Jain
Web Developer
United States United States
No Biography provided

Comments and Discussions

 
GeneralMy vote of 5 PinprofessionalRaja Sekhar S3-Jun-13 19:40 
GeneralMy vote of 5 PinmemberChesare29-Sep-11 10:13 
GeneralMy vote of 4 PinmemberCJ18-Jun-11 4:28 
Generalbinding two textboxes in two different tabs with same property Pinmemberyagz81200525-May-11 19:23 
GeneralDatabinding and Event Firing Pinmemberjasona2214-Dec-10 8:15 
GeneralMy vote of 5 PinmvpLuc Pattyn27-Oct-10 16:48 
QuestionComboBox Bound to Related Table Pinmemberstixoffire30-Jun-09 13:29 
GeneralVery nice. Pinmember377988621-May-08 19:39 
GeneralOpen source alternative to data binding PinmemberMichael L Perry9-Apr-08 16:18 
GeneralNavigating Data Sets Pinmemberandrewf20-Mar-08 4:12 
QuestionNot able to save Control data binded to Datasource when Control is still in edit mode. Pinmembervinutha kempanna5-Dec-07 23:17 
QuestionHow to bind two different controls to same datasoure but different rows? Pinmembervinutha kempanna24-Sep-07 22:07 
Generaltxt2.DataBindings.Add("Text", oDt, "GetDateTime",1,0,0,"yyyy/mm/dd") Pinmembersuperbem17-Aug-07 14:31 
GeneralData Binding PinmemberShar0n1-Feb-07 0:50 
AnswerRe: Data Binding Pinmemberprasadengg200628-Jul-07 0:48 
QuestionDataBindings in the PictureBox? PinmemberGeoffreyOng7-Sep-06 22:20 
AnswerRe: DataBindings in the PictureBox? Pinmemberstixoffire30-Jun-09 12:51 
General2D Array binding (Compact Framework) Pinmembermatiasls28-Mar-06 6:11 
GeneralProblem in Complex Binding PinmemberArchana19778-Oct-05 2:30 
GeneralFormating complext binding PinmemberBnaya Eshet7-Jan-05 4:03 
GeneralSimple binsing to a simple COM property PinmemberMasariello20-Aug-04 2:21 
GeneralRe: Simple binsing to a simple COM property PinmemberMaruis Marais11-May-05 15:54 
Generalwant to hyperlink the data retrieved Pinsussractim20-Aug-04 1:41 
QuestionHow to set color to some rows and multiselect rows in datagrids? PinmemberJum3065527-Jul-04 17:52 
AnswerRe: How to set color to some rows and multiselect rows in datagrids? PinmemberMaruis Marais11-May-05 15:58 
GeneralData Insert PinsussEduardo Escolar10-Jul-04 18:32 
GeneralPermission to use images PinmemberSijin25-Jun-04 19:59 
GeneralUndo/Redo - Windows Forms, Data Binding and Business Objects Pinmembersancreations10-May-04 20:48 
Generalimage from access PinsussPrasadVarier29-Feb-04 18:41 
GeneralRe: image from access PinmemberAlan Cossey4-May-04 9:29 
GeneralRe: image from access Pinmemberthomasdev17-May-04 12:34 
Generalbinding dataset and list in detail view Pinsussayesha_ucit19-Feb-04 3:33 
GeneralUsing Dataset...Format Currency...Can't Change Value PinmemberSlonocode17-Jan-04 12:22 
GeneralUpdating Databound control when bound property changes PinmemberBinkiboy12-Dec-03 6:38 
GeneralRe: Updating Databound control when bound property changes Pinmembervolkartp2-Feb-04 2:38 
GeneralRe: Updating Databound control when bound property changes PinmemberBinkiboy2-Feb-04 2:47 
GeneralRe: Updating Databound control when bound property changes PinsussJustAnEngineer7-Apr-04 6:20 
GeneralRe: Updating Databound control when bound property changes PinsussRoni Burd11-Oct-04 11:13 
GeneralRe: Updating Databound control when bound property changes Pinmembersman29-Jul-04 5:40 
GeneralRe: Updating Databound control when bound property changes PinsussAnonymous21-Oct-04 13:52 
GeneralRe: Updating Databound control when bound property changes Pinsusssbsaxman19-Nov-04 10:26 
GeneralRe: Updating Databound control when bound property changes Pinmembercmerkens16-Jun-05 4:03 
GeneralRe: Updating Databound control when bound property changes Pinmemberjackyjak28-Jul-05 0:27 
GeneralRe: Updating Databound control when bound property changes Pinmemberwiztech303-Jul-06 8:15 
GeneralRe: Updating Databound... (INotifyPropertyChanged) PinmemberErikPhilips17-Jul-07 20:31 
GeneralDataBinding with combobox and selection Pinmemberraju_shrestha24-Nov-03 16:32 
GeneralRe: DataBinding with combobox and selection Pinmembercmerkens29-May-05 23:01 
GeneralUsing databindings with negated boolean PinsussMark Kettlewell10-Nov-03 6:13 
GeneralThanks for the time PinmemberTLWallace26-Sep-03 14:50 
GeneralUpdate datagrid PinmemberMoishe16-Jun-03 18:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.141029.1 | Last Updated 16 Feb 2003
Article Copyright 2003 by Tarun Jain
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid