|
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
- 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.
- .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.
- Control over the Databinding process by using events. This is discussed in more detail later in the article.
Disadvantages of DataBinding
- More optimized code can be written by using the unbound or traditional methods.
- 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.
- Arrays
- DataColumn
- DataTable
- DataView
- 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.
Dim WithEvents oBinding As Binding
Private Sub Form2_Load(ByVal sender As Object, ByVal e As System.EventArgs) _ Handles MyBase.Load
oBinding = New Binding("Text", oDt, "GetDateTime")
txt1.DataBindings.Add(oBinding)
txt2.DataBindings.Add("Text", oDt, "GetDateTime")
End Sub
Private Sub oBinding_Format(ByVal sender As Object, ByVal e 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
- Added a new C# sample which does the same thing as the VB.NET example.
| You must Sign In to use this message board. |
|
| | Msgs 1 to 25 of 59 (Total in Forum: 59) (Refresh) | FirstPrevNext |
|
|
 |
|
|
I found this article as very neat and elaborative in explaining the concept.
I got cleared some doubts, by reading the post.
5 from me:
3779886
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
You might want to check out this open source alternative to data binding at http://codeplex.com/updatecontrols. With Update Controls, you don't have to mess with currency managers and property managers. Update Controls work with your plain old C# or VB objects with no special interfaces or binding contexts.
One of the biggest problems I see with .NET data binding is that it still encourages a direct link between user interface components and data elements. Sure, you don't have to bind directly to the database anymore. But when binding directly to properties of an object, it is difficult to interject custom business logic.
Update Controls work even through business logic, no matter how complex or indirect. Each control monitors all of the data elements that your business logic looks at in order to determine a value to display. When one of those data elements changes, the control calls your business logic again. It's all automatic and incredibly easy to use.
Michael L Perry http://adventuresinsoftware.com http://updatecontrols.net
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
I have a project that I am trying to bring across from VB6 into .NET (2005). The project does it's own database navigation of an access database. This has worked well under VB6. The conversion has not imported the data set as a .NET dataset, but rather built a VB class. I wish to rebuild this part of the project as a proper VB.NET data source.
After researching what I need to do, I keep seeing that I need to use the OleDBConnection and OleDBDataApapter to enable a data set to be generated, then I can use the binding context to navigate the data set.
I do this, and I use the Fill method (on the adapter) to fill the data set. This fills all my bound controls with the first record brillantly. My problem that I have is that my navigation buttons do not change the values in my data bound controls. The first record stays there. I created two records, so I know there is more than one. When I place a message box to check what is happening to the position property, it does change, but not the data on my form.
Is someone able to shed some light on what the problem might be?
I am running VS.NET 2005 on Vista Bussiness. I am not sure if this has any bearing to the cause of the problem.
Any assistance would be greatly appreciated.
|
| Sign In·View Thread·PermaLink | 2.00/5 (1 vote) |
|
|
|
 |
|
|
Hi,
I my application i have a TextBox (tbName) control which is binded to a datasource.
tbName.DataBindings.Add(new Binding("Text", dsDetails,"AccountInfo.name"));
Now when the text box control is still in Edit mode and has Focus and i try to save the changes made ,the changes made to the TextBox will not be saved back to the Datasource.
How can i End Edit on the TextBox Control. Any help on this Appreciated.
Regards Vinutha
|
| Sign In·View Thread·PermaLink | 2.00/5 (1 vote) |
|
|
|
 |
|
|
Hi,
I have two textbox ,mtbPhone1 and mtbPhone2,these two textbox are binded to the same datasource.However mtbPhone1 has to fetch the data from first row in the table and the mtbPhone2 has to fetch the data from second row in the table. //Binding the Control mtbPhone1.DataBindings.Add(new Binding("Text", dsConfiguration, "PhoneLine.prefix")); mtbPhone2.DataBindings.Add(new Binding("Text", dsConfiguration, "PhoneLine.prefix")); I tried setting the position property of the currency Manager, But no result. CurrencyManager cm = (CurrencyManager)this.mtbPhone1.BindingContext[dsConfiguration, "PhoneLine"]; cm.Position = 0; CurrencyManager cm = (CurrencyManager)this.mtbPhone2.BindingContext[dsConfiguration, "PhoneLine"]; cm.Position = 1;
How can this be accomplished.
And also if a control(say Textbox) is binded to a Datasource, and if the control value is edited and the control is still in edit mode ... in meanwhile if the application is closed will the changes be updated back to the datasource?
Regards Vinutha
|
| Sign In·View Thread·PermaLink | 1.00/5 (1 vote) |
|
|
|
 |
|
|
Is more elegant to me 
txt2.DataBindings.Add("Text", oDt, "GetDateTime",1,0,0,"yyyy/mm/dd")
Superbem
|
| Sign In·View Thread·PermaLink | 2.00/5 (2 votes) |
|
|
|
 |
|
|
 |
|
|
 |
|
|
Hello, i have the problem in the displaying my image after the image was perform the databindings.
how to display my picture after perform the databingings?
the code below can not run the display. "picbox1.databindings.add("Text", dsProperty.Tables("Property"),"Picture")" why?
|
| Sign In·View Thread·PermaLink | 1.67/5 (2 votes) |
|
|
|
 |
|
|
How can I bind a 2D array to a datagrid? I need to develop a virtual list. All items should be loaded when the user scrolls the grid. A DataTable is a solution but it spends a lot of time loading null rows.
|
| Sign In·View Thread·PermaLink | 1.00/5 (2 votes) |
|
|
|
 |
|
|
Hi
Than was very good article.
Here I am facing really weird issue.
I have a collection
public class DeptList : BindingList { public DeptList() {
}
private int _total = 90;
[Bindable(true) , Browsable(true)] public int Total { get { return _total; } set { _total = value; } }
}
Now I want to bind this Total property to TextBox.
DeptList list = new DeptList(); bindingSource1.DataSource = list; this.textBox1.DataBindings.Add("Text", list, "Total");
But it is giving me error.
Any solutions to this problem.
I tried defining another class which is not collection. But has property Depts of Type DeptList. If I define Total property in this class it works fine. But I am not much happy with this solution.
Please advise.
Regards Archana
|
| Sign In·View Thread·PermaLink | 1.00/5 (2 votes) |
|
|
|
 |
|
|
Do you have any idea how to control the format of complex binding (like setting format to specific DataColumn)?
Bnaya Eshet
.NET Expert and Chief Architect at Wise Mobility
|
| Sign In·View Thread·PermaLink | 1.56/5 (3 votes) |
|
|
|
 |
|
|
Hi, can anyone help with binding to simple COM properties, please? I implemented the following for a CObj class in attributed C++.
__interface IObj : IDispatch { [propget, bindable, displaybind, id(1)] HRESULT AProperty([out, retval] DOUBLE* pVal); [propput, bindable, displaybind, id(1)] HRESULT AProperty([in] DOUBLE newVal); }; // _IObjEvents __interface _IObjEvents { [id(1)] HRESULT APropertyChanged([in] IObj* pIObj, [in] DOUBLE newVal); };
Binding fails in VB.Net if I write
Dim obj As IObj obj = GetObject("", "CObj") // THIS WORKS FINE obj.AProperty = 123.0 // THIS WORKS TOO TextBox.DataBindings.Add("Text", obj, "AProperty") // THIS FAILS
What else do I need next to the property to be able to bind to it?
I really hope I can fix this. It would mean a lot. Thanks Alessio
|
| Sign In·View Thread·PermaLink | 1.00/5 (1 vote) |
|
|
|
 |
|
|
For the data binding to be able to take place the data source object (in your case the IObj object) needs to inherit from IList somewhere in the object hierarchy.
The other thing I think is that you aren't able to data bind to interfaces, but I am talking under correction on the interface issue.
|
| Sign In·View Thread·PermaLink | 1.33/5 (2 votes) |
|
|
|
 |
|
|
Hi, Let me make it clear the thing i mentioned in the subject. I have displayed the data from the database using datagrid.Suppose we have three column names in the displayed employee table viz. employeeid,employeename and division. When the data are displayed, these three fields are the output.Now I want that, the employee names that are displayed are the hyperlinks to another page where their personal informations are stored. This was the application I was trying. Can you tell me how to do that ? I dont want to use the hyperlink column as every member in this column navigates to the same page and it leaves no option to navigate to different pages from different fields.
|
| Sign In·View Thread·PermaLink | 1.33/5 (3 votes) |
|
|
|
 |
|
|
Hello All.
I have some question about DataGrids in VB.net windows forms 1. How to fix some columns (1st , 2nd,.. cols) of DataGrid when scroll data? 2. How to set different color to some rows? 3. How to multiple selection rows of data grid? And when click some button action with rows selected?
Thank you for advance
|
| Sign In·View Thread·PermaLink | 1.00/5 (3 votes) |
|
|
|
 |
|
|
Check out the following pages with ample examples on how to jiggle the win forms datagrid:
http://www.syncfusion.com/faq/windowsforms/Default.aspx
I am sure you'll find all you need there...
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hi there! I am trying to populate a database using a stored procedure to insert records in the database. My question is: How should I pass the parameters requiered by the stored procedure(using code) or... using a Windows form, how can I send the contents of the textboxes to the database in order to populate it(using code)? Thanks,
|
| Sign In·View Thread·PermaLink | 1.71/5 (7 votes) |
|
|
|
 |
|
|
Hey Tarun,
Can i use some of your images in a presentaton i am doing on Data Binding, I would be really grateful.
Very informative article btw.
I always think that the idea of a compiler that compiles another compiler or itself is rather incestuous in a binary way. - Colin Davies
My .Net Blog
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
 Maintaining state of Business Object and User Interface to provide N-No of Undo/Redo capability. User Interface and Business Object synchronization (After any Undo/Redo operation, the UI should focus the Bound control whose value is changed).
"As far as maintaining the state of the business object is concerned, this problem is resolved. But the only trouble i am facing is "The User Interface must respond and set the focus to the underlying control"
Problem Description:
The undo/redo action should allow user-initiated changes to be reversed and re-applied. It is necessary to detect user-initiated changes to the business object. It would be insufficient to monitor the various property change events emitted by the business object because the event handler would be unable to tell whether the change originated from the UI. Furthermore, it would be insufficient to monitor the validated event because this event provides no details about the binding activity (before/after property values). Also some modifactions to the state of the object might result from a method invocation.
The requirement is to find an event which gets fired every time the Object property is changed or reset. As well as this event should notify us the current bindingContext. The binding class in .Net Framework provides us 2 such events viz Format and Parse and these two events proved to be insufficient because of their nature of occurance. (The Format event gets fired every time before and after the object properties are changed and there is no notification of New and Old values. The Parse event gets fired every time when the property is changed through the UI and will not get fired when the property is changed through the code)
Research over BindingManagerBase revealed that the Push /Pull data methods are not virtual methods, they are only protected methods in BindingManagerBase, so it seems deriving from BindingManagerBase could not customize them, also the BindingContext only accepts the class which base is BindingManagerBase so create a wrapper class for the PropertyManager class also might not work
In order to achieve the above mentioned objective, we are thinking of building a CommandManager which would sit between the Presentation layer and Business layer. CommandManager will be responsible for interacting with the Business layer and maintaing the UI state as well as the Business Object's current state. Any property changes/method calls to the Business Object will pass through the CommandManager. This solution requires the team developers to write their own Custom binding over the .Net Framework and seems to be a possible but too much of an effort.
|
| Sign In·View Thread·PermaLink | 2.43/5 (5 votes) |
|
|
|
 |
|
|
i am using msaccess as database.i put a field as image data type as OLEOBJECT.Now i want to display it in my vb.net form.Please help me.
|
| Sign In·View Thread·PermaLink | 1.00/5 (1 vote) |
|
|
|
 |
|
|
I don't know the answer to the question you put, but, if it is possible, I would suggest you don't store images in an Access database. It causes the size of the database to grow enormously. Normally, people store the images outside as a file and just store the path to the file in the Access database.
Alan Cossey
|
| Sign In·View Thread·PermaLink | 3.00/5 (2 votes) |
|
|
|
 |
|
|
 |
|
|
Hello all! i want to display more than one columns of a dataset table in a list with detail view. can I? How? thanx
|
| Sign In·View Thread·PermaLink | 1.45/5 (10 votes) |
|
|
|
 |
|
|
I have a few textboxes bound to a dataset. The format event is to display "short date". I have no problems changing the value in the textbox and having the dataset reflect the changes.
I also have a few textboxes bound to the same dataset. The format event is to display "c" (currency). If I change the value in the textbox...as soon as I leave the textbox the value reverts back to it's original.
|
| Sign In·View Thread·PermaLink | 1.50/5 (8 votes) |
|
|
|
 |
|
|
General News Question Answer Joke Rant Admin
|