Data binding Concepts in. NET Windows Forms

Source: Internet
Author: User

"Go" Data binding concepts in. NET Windows Forms

A detailed look at the concepts involved in data binding and controlling data binding.
    • Example showing how to control DataBinding vb.net-22 Kb
    • Example showing how to control DataBinding C #-Kb
Introduction

This article gives a overview of data binding in the. NET framework. Microsoft have beefed the data binding features considerably in. NET which have made data binding a compelling option to Tie your front-end to data sources. I have the concentrated on. NET Windows Forms data binding.

What is DataBinding?

DataBinding is a powerful feature provided by the. NET framework, 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 and any changes made to the datasource be reflected immediately in the visual E Lement 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 is used is 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 has the flexibility to control the databinding process with the result of the most developers avoided th e Use of databinding.

DataBinding with. NET

The. NET Framework provides a very flexible and powerful approach to databinding and allows the programmer to has a fine Control over the steps involved in the whole process. One of the biggest improvements with. NET have been the introduction of databinding to Web pages through the use of. NET SE Rver-side Web Controls. Hence, building Data driven Web applications has been greatly simplified. Please note the article only deals with data binding in. NET Windows Forms.

Advantages of DataBinding
    1. Databinding in. NET can is 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 '.
    2. . NET automatically writes a lot of databinding code for your in the background (you can see it in "Windows Generated code" section), so the developer does is not a spend time writing code for basic databinding, but still has the flexibility O F Modifying any code that he would. We get the benefits of bound as well as unbound approach.
    3. Control over the Databinding process by using events. This was discussed in more detail later in the article.
Disadvantages of DataBinding
    1. More optimized code can is written by using the unbound or traditional methods.
    2. Complete flexibility can is achieved by using the unbound approach.

Databinding Concepts

For databinding-to-take-place data provider and a data consumer should exist so a synchronized link was established be Tween the other. 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. The. NET any class or component this implements the IList interface is a valid DataSource. If a component implements the IList interface then it's transformed into an index based collection.

Some of the classes, the IList interface in the NET framework is given below. Please note this implements the IList interface is a valid data provider.

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

Please note this IList  interface only allows the bind at run time. If you want-to-support DataBinding at design time, you'll have to implement the interface as well IComponent  . Also Note This cannot bind to datareaders in Windows Forms (you can in Web Forms).

The. NET framework supports simple and complex DataBinding. Simple databinding are supported by controls like Textboxes. In simple databinding, only one data value can is displayed by the control at a time. In complex databinding, which was 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 are very important. The diagram below gives an overview of the dataflow and the objects involved.



In. NET, controls can has many properties that can is bound to a DataSource. Each databound is a associated Binding object. Since A control can have many Binding objects, the control has a collection (instance ofControlBindingsCollection Class) of all the Binding objects. Also remember that different properties of the same control can being bound to different datasource ' s.

Each Binding object talks to aCurrencyManager or aPropertyManager.CurrencyManager andPropertyManager Classes merit a little explanation, as they are important.CurrencyManager andPropertyManager is derived from the base classBindingManagerBase. The purpose ofBindingManagerBase Class is to maintain the concurrency between the DataSource and the control. Of the classes, theCurrencyManager is used when the DataSource implements theIList Interface. Examples of such datasources areDataView,DataSet,ArrayList etc. TheCurrencyManager Can is used for simple as well as complex databinding. However, thePropertyManager is used when the datasource are an instance of a user-defined class. The Control's property was bound to the property exposed by this object. PropertyManager can only is used for simple databinding.

As a rule of thumb if you want your class to is a DataSource, you should useCurrencyManager When the your class is a data container. However, if you is interested in the binding a control to the properties exposed by your own class and then using aPropertyManager is easier, since don't have a to implement theIList Interface.

Since A form can contain many controls each binding to a different DataSource, a class was needed to manage theCurrencyManager andPropertyManager Objects. Therefore, each of the Windows Form in. NET have a default BindingContext object associated with it. But, you can always create more BindingContext objects on the form. TheBindingContextObject is a collection ofCurrencyManager andPropertyManager Objects.

To summarize:

  • A control can has many properties that can be bound.
  • Each databound property of the control have an associated Binding object.
  • The all Binding objects for a control was contained by the control's property DataBindings  , which was an instance of ControlBindingsCollection  class.
  • Each databinding object talks to a CurrencyManager  or PropertyManager  object.
  • CurrencyManager and is derived from the PropertyManager  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 is 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 Suppo RTS events. This enables us to change the data passed between the Control and the datasource.

A Quick look at the figure below can and understand this behaviour.



The diagram above depicts how. NET Windows Forms databinding have been made flexible by making use of the events generated by Binding and BindingManagerBase classes.

The Binding object exposes the Events:format and Parse. The Format event is triggered twice. First time the data is pushed from the datasource to the control and the second time when the DataSource is changed and Da TA is updated to the control. The parse event is triggered once if the data is pulled from the control to the datasource.

The Currency Manager (derived from theBindingMangerBase Class) exposes three events:CurrentChanged,PositionChanged and itemchanged.CurrentChanged is triggered when the bound value changes; PositionChanged was triggered when the position property had changed and ItemChanged was triggered when the current item had Changed. Please note that the PropertyManager class supports is only 2 events:currentchanged, positionchanged.

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

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

'the binding object must is declared with the keyword "WithEvents" in order <BR> ' for us Mat and parse events.Dim WithEventsObinding asBindingPrivate SubForm2_load (ByValSender as Object,ByValE asSystem.EventArgs) _
Handles MyBase. Load
'A new Binding object declared above using "WithEvents" is explicitly
' Created that binds the text field to the ' GetDateTime ' property of the
' Mydatetime class. The binding object is then added to the textbox ' s
' DataBindings collection.Obinding =NewBinding ("Text", ODt,"GetDateTime") txt1. Databindings.add (obinding)'Here , the binding object was not explicitly created and hence 'no events would triggered and the datetime is displayed in
' "Mm/dd/yyyy hh:mm:ss" 'format only.Txt2. Databindings.add ("Text", ODt,"GetDateTime") End Sub 'This event was triggered right before the Txt1 ' s text field displays the
' datetime value is itobtains from the ODt object (the DataSource). Here, we
' has changed the format of display to "Mm/dd/yy" although the actual
' Data pulled from the oDt is in ' mm/dd/yyyy hh:mm:ss ' format. Private SubObinding_format (ByValSender as Object,ByValE
asSystem.Windows.Forms.ConvertEventArgs)HandlesObinding.format E.value=Format(E.value,"Mm/dd/yy") End Sub
In the example, there is and 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, 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 the Refore make the example self contained. However, the same code can be applied to format the data when the datasource are populated from SQL Server database. Please refer to the sample code for better understanding of what to use events.

Change Log
    1. Added a new C # sample which does the same thing as the vb.net example.
License

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

A List of licenses authors might use can is found here

Share about the Author Tarun Jain
"Turn" http://www.codeproject.com/Articles/3665/Data-binding-concepts-in-NET-windows-forms

Data binding Concepts in. NET Windows Forms

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.