Home

Control Data Binding

 

Description

When you want to visually deal with records of a database from a Windows application, you may simply want to view the data. Although Microsoft Visual Studio 2005 provides various effective means of binding data to Windows controls, sometimes, you may want to manually bind the controls. To do this, you can use a DataSet object.

The DataSet class allows you to access any type of information from a table. These include table's object name, the columns (and their properties), and the records. This means that you should be able to locate a record, retrieve its value, and assign it to a control. Probably the only real problem is to make sure your DataSet object can get the necessary records. The records could come from a database (Microsoft SQL Server, Oracle, Microsoft Access, Paradox, etc).

Here is an example of binding data to two text boxes to the records of a Microsoft SQL Server table:

Imports System.Data.SqlClient

Public Class Central

    Private Sub btnLoad_Click(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) _
                              Handles btnLoad.Click
        Dim conDatabase As SqlConnection = _
        New SqlConnection("Data Source=(local);Database='bcr1';" & _
              "Integrated Security=true")
        Dim cmdDatabase As SqlCommand = _
		New SqlCommand("SELECT * FROM dbo.Employees;", conDatabase)

        Dim dsEmployees As DataSet = New DataSet("EmployeesSet")
        Dim sda As SqlDataAdapter = New SqlDataAdapter
        sda.SelectCommand = cmdDatabase
        sda.Fill(dsEmployees)

        Dim recEmployee As DataRow = dsEmployees.Tables(0).Rows(0)

        txtFirstName.Text = CStr(recEmployee("FirstName"))
        txtLastName.Text = CStr(recEmployee("LastName"))

        conDatabase.Close()
    End Sub
End Class
 

Home Copyright © 2007-2012 FunctionX