jump to navigation

Binding Data To Controls July 1, 2008

Posted by prasu in : Databases, Technical, VB.NET , add a comment

In 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:

  1. Drag three Labels, three Textboxes and two buttons to a new Windows form.
  2. Change the text property of the three Labels to Name, City and Date of Birth.
  3. Change the text property of the buttons to Next and Previous.
  4. Double click on the form and within the form_load method type the code as shown below.
  5. Double click on the Next button and within the Click type the code-
    bs.MoveNext()
  6. 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:

  1. 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.
  2. bs.MoveNext() binds the next record in the table to the controls (as long as a ‘next’ exists).
  3. bs.MovePrevious() binds the previous record in the table to the controls (as long as a ‘previous’ exists).


Warning: stristr() [function.stristr]: Empty delimiter in /home/tekyt17/public_html/dotnet/wp-content/plugins/wassup/wassup.php on line 2093