By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,314 Members | 2,155 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,314 IT Pros & Developers. It's quick & easy.

An Interesting use of data binding

P: n/a
I am not sure how many are aware of this sort of data binding,
but as it is new to many (classic) VB developers I thought I
would post this once just to let people know of its availablility.

There are cases where properties of one object is dependant on
a property of another object. For a common example, when you
bind an ArrayList to a ComboBox using the combo's DataSource
property, the combo box fills up with items from the array list.

Attaching a property of one control to the property of another
is also possible using binding. For example, if you have a
checkbox as an option, and a few other controls that should be
enabled when that checkbox is checked, you can do that by
writing appropreate code in the checkbox changed event, or you
can do it using data binding.

In this case you can bind the Enabled property of the secondary
control(s) to the Checked property of the checkbox. There is
also the possiblility of inserting code into the binding process
to be called when the change is underway.

I have included an example of both methods below. A simple
binding of the two controls, is just one line of code. To
show how to insert code into the process, I've bound one
textbox that is enabled when the checkbox is checked, and
another Textbox that is disabled when the checkbox is checked.

To see it in action, add two Textboxes and a Checkbox to a new
form and paste in the code below.

I just thought it was rather neat and tidy where one line of
code binds the two controls, instead of filling a Changed
event (handler) with the needed code....


Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Checked/enabled, not checked/not enabled
TextBox1.DataBindings.Add(New Binding("Enabled", CheckBox1, "Checked"))
TextBox1.Text = "Simple"

' Checked/Not enabled, not checked/enabled
Dim binder As Binding = New Binding("Enabled", CheckBox1, "Checked")
AddHandler binder.Format, AddressOf InvertBoolean
TextBox2.Text = "Inverted"
End Sub

Public Sub InvertBoolean(ByVal Sender As Object, ByVal cEvent As ConvertEventArgs)
If cEvent.Value.GetType Is GetType(Boolean) Then
cEvent.Value = Not CType(cEvent.Value, Boolean)
End If
End Sub

Nov 21 '05 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.