Through careful use of databinding, your UI code can be very light weight.
There are two forms of databinding that we need to discuss, binding to properties of objects and binding to a list of objects – which often binds to properties of the individual objects.
First, let’s deal with the less talked about binding to properties. The code to setup a binding to a particular property on an object is fairly simple. The following snippet binds the text property of the _txtName textbox to the name of a person.
This assumes several things. First of all, it assumes that the TextBox has a Text property. Second, it assumes that the person is not null and lastly, that the person has a valid property called name. Once you work through those assumptions, the TextBox in question will not only show but allow you to edit the person’s name with that one line of code. If, however, instead of a person object, you have a table with rows of people, you will bind as follows.
As a quick note, on the full
However, this is a shortcoming of the
Back to the original thought, as this is a simple textbox, this is only able to bind to one row at a time so it’s going to enlist the BindingManagerBase for the form to pick which row is bound. The BindingManagerBase controls the databinding for a particular object for all of the bound sub-controls of the control from which it was returned. Most often, it is used to control the bindings for an entire form, as I’ve done in the sample, but it can also be used on a particular Tab or Panel. To get the BindingManagerBase, use the BindingContext for the container in question to retrieve it as follows.
At this point, you can use the BindingManagerBase to control the position in the list and thus the current row bound by the TextBox by setting its Position or to monitor changes to the object by subscribing to the CurrentChanged event.
This will allow you to cycle through the list easily.
The second form of databinding, binding to lists, is even easier. The code is as follows.
Setting the DataSource on the list requires that the list (or table in this sample)
There are some benefits to combining these methods of databinding. For example, if you bind the table to the list and bind the textbox to the same table – the listbox will automatically keep track of the positioning of the BindingManagerBase.
In conclusion, there is very little need to write a lot of UI code anymore. Instead, leverage databinding to your advantage to keep your UI lightweight and responsive.
For a full code listing download the sample code below.