Binding Data To Controls July 1, 2008
Posted by prasu in : Databases, Technical, VB.NET , add a commentIn practical applications it is not always convenient to retrieve data in DataGridView (as done in a previous example). Data can also be retrieved in a more elegant manner and bound to Controls like TextBoxes or Labels. For this purpose, we come across a new object type known as BindingSource.
Binding Source binds the data from a column in a table to a control.
For this example, we will be using the same table as we did for the DataGridView Example (my previous post)
Example:
- Drag three Labels, three Textboxes and two buttons to a new Windows form.
- Change the text property of the three Labels to Name, City and Date of Birth.
- Change the text property of the buttons to Next and Previous.
- Double click on the form and within the form_load method type the code as shown below.
- Double click on the Next button and within the Click type the code-
bs.MoveNext() - Double click on the previous button and within the Click event type the code-
bs.MovePrevious()
Public Class Form3
Dim cn As New Odbc.OdbcConnection("Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=mydb; User=root;Password=;")
Dim cmd As New Odbc.OdbcCommand
Dim adp As Odbc.OdbcDataAdapter
Dim ds As New DataSet
Dim bs As BindingSource
Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cn.Open()
cmd.Connection = cn
cmd.CommandText = "Select * from mytable"
adp = New Odbc.OdbcDataAdapter(cmd)
adp.Fill(ds, "mytable")
'Binding Statements Follow
bs = New BindingSource(ds, "mytable")
'Bind the name field to first textbox, type of data as text
Me.TextBox1.DataBindings.Add("text", bs, "name")
Me.TextBox2.DataBindings.Add("text", bs, "city")
Me.TextBox3.DataBindings.Add("text", bs, "dob")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
bs.MoveNext()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
bs.MovePrevious()
End Sub
End Class
In the above code:
- The name,city and the dob (Date of Birth) columns of the table named ‘mytable’ (this is the same table I used in an earlier post) is bound to three textboxes namely textbox1,textbox2 and textbox3 respectively using statement- Me.TextBox1.DataBindings.Add(”text”, bs, “name”) and so on.
- bs.MoveNext() binds the next record in the table to the controls (as long as a ‘next’ exists).
- bs.MovePrevious() binds the previous record in the table to the controls (as long as a ‘previous’ exists).
