Binding two Windows Forms controls

Recently, I came across a small windows application where the developer had difficulties to activate controls based on a another one. Typical example is when you want to activate a textbox sitting next to a checkbox. The developer chose to use the CheckedChanged event of the Checkbox, and to modify the Enabled property of the Textbox accordingly. The problem is you have to properly initialize the CheckState, and Enabled property of the controls to keep them both in sync from the beginning.

Then I showed him how to bind two controls directly. Most developers know about binding a control to datasource, but few of them know that it is also possible to bind to another control.

The following line shows how to do that :
myTextbox.DataBindings.Add("Enabled", myCheckbox, "Checked");

This line simply binds the Enabled property of the Textbox to the Checked property of the Checkbox. By doing that, there is no need to initialize each property nor to respond to any event.
The only drawback is that there is no designer support. You have to create the binding manually, the designer only supports binding to data. Usually, I put this line in a InitializeBinding method (called just after InitializeComponent).

Popular posts from this blog

Adding a delay before processing Textbox events

Handling exceptions the right way in WCF (part 2)

Create a draft release and start it using the TFS REST API