Tuesday, January 29, 2013

Simple Data Binding


Links to previous articles in this series:

Interactive Controls and Simple Data Binding
In this tutorial I am going to introduce you to a couple of new controls that users can manipulate, and then tie it together with a function from the latest tutorial (last one in the links above). I will also introduce some simple data binding which will reduce the code you need when linking different controls and data sources.

Trackbar Control
You may be familiar with the trackbar control, it is essentially a slider that allows a user to change a value by sliding an arrow, the most prevalent example I can think of is the volume control on most music and video apps.
Start a new project (it’s a good idea to create new projects when possible with these tutorials giving them a descriptive name so you can easily reference them when you are working on future projects) named TrackbarDataBinding. Look in your toolbox for the trackbar control and add it to the form as well as a textbox. Drag the squares on the trackbar to make it about 3 inches wide. Name your textbox txtTrackbarValue and your trackbar trackUserInput.
First, let’s go through some of the common properties of the trackbar. Click the trackbar and go to the properties box. To make the properties easier to find, you can click the sort alphabetically icon on the properties box.


Find the Maximum property and set it to 100, this makes the maximum value of the trackbar 100. Leave the Minimum at 0. So we can see what some of the other settings do let’s add a piece of code that will put the current value into our textbox. Double-click the trackbar, this should open the code page and create a scroll event. Place the following line in the event and click run.
Me.txtTrackbarValue.Text = Me.trackUserInput.Value
Click the trackbar arrow and drag it around, notice that the textbox value changes as expected. Now set the trackbar back to zero, then click another point somewhere along the control, the value should increment by 5 each time you click. Page Up and Page Down perform the same task, this jump of 5 is controlled by the Large Change property. If you press the left or right arrow or the up and down arrow the number will increment by 1, this is the Small Change property. Another useful property is Orientation, this will let you display the trackbar horizontally or vertically. Go ahead and play around with the settings and get comfortable with how they work.

Databinding
Databinding is a way to bind controls and data together, similar to what we did above by setting the textbox’s text property to the value of the trackbar. The benefit comes in when you need to do something a little more complex. From the example above, imagine that we want to let the user choose whether to use the trackbar, or just type the value they want in the textbox. To do this in code, you would basically do what we have already done, then you would need some sort of event that would know when the textbox had been updated so it could then set the value of the trackbar. Databinding simplifies this greatly. Delete or comment the line of code you already have, then create a form load event by going back to your form and double-clicking the top bar of the form. Now we can create the binding when the form loads and the two controls will be tied together whenever the application runs and stay that way unless you change it.
In the form load event add the following line.
Me.txtTrackbarValue.DataBindings.Add("Text", Me.trackUserInput, "Value")
The first part just tells that we are going to add some sort of databinding to our textbox. The “Text” piece says that we will be binding the text property of the textbox. The middle section tells what control we are binding to, and “Value” says that we are binding to the value property of the trackbar. That’s it, run the application and try out the trackbar, then then try typing a number (0 to 100) and press tab to leave the textbox, the trackbar should now show the value you typed in the textbox.
While this may not seem like it saves a lot of code, once you are binding multiple controls or tying into a database the usefulness will become apparent quite quickly.

Integrating a Function
Now let’s tie our trackbar to a function. Start by adding a label to the form from the toolbox and name it lblMultiply, a label is similar to a textbox but is for displaying data only; it does not accept user input.
As you did in the last tutorial add a function and the required parameters:

Function multiplication(intVal, intMult)
        multiplication = intVal * intMult
 End Function

 Back in your trackbar scroll event (double-click the trackbar on the form if you deleted the event) type:

Me.lblMultiply.Text = multiplication(Me.trackUserInput.Value, 10)

This will set the text of the label to the result of 10 times the trackbar’s value. Run the application and test out the trackbar, the label should update with the formula result, but notice that if you change the textbox manually the trackbar updates but the label does not. The reason for this is that the event we created was for the scroll event of the trackbar. Remember that the binding is tied to the trackbar’s value, this sets the position of the trackbar but it does not cause it to scroll, that can only be done by the user. How do we fix this then? Well, we know that the value of the trackbar changes, so we need to create an event that fires when the value changes. To do this, you need to be introduced to another helpful feature of .NET. Near the top of the screen you will see two dropdowns, the content of which depends on where your cursor is at the time.



These dropdowns help you create events, showing all possibilities for the selected object. Drop the left one down to choose the object, in our case trackUserInput. The default is the scroll event and if it has not already been created, it will be. Now drop down the right box and select ValueChanged, this should create a new ValueChanged event. Move your code to set the labels text to this event, it should now look like this.

Private Sub trackUserInput_ValueChanged(sender As Object, e As EventArgs) Handles trackUserInput.ValueChanged
        Me.lblMultiply.Text = multiplication(Me.trackUserInput.Value, 10)
End Sub

Now run your application and test the trackbar as well as the textbox, you should see that the label updates with either one. The lesson here is that you have to think through what your events are doing, if something isn’t working look through your events and see if you can find something else that might work.
Here is the code that gets everything to work in case you ran into trouble

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.txtTrackbarValue.DataBindings.Add("Text", Me.trackUserInput, "Value")
    End Sub
    Function multiplication(intVal, intMult)
        multiplication = intVal * intMult
    End Function
    Private Sub trackUserInput_ValueChanged(sender As Object, e As EventArgs) Handles trackUserInput.ValueChanged
        Me.lblMultiply.Text = multiplication(Me.txtTrackbarValue, 10)
    End Sub

End Class


No comments: