How to: Bind a Windows Forms Control to a Factory Object

 

When you are building controls that interact with data, you will sometimes find it necessary to bind a control to an object or method that generates other objects. Such an object or method is called a factory. Your data source might be, for example, the return value from a method call, instead of an object in memory or a type. You can bind a control to this kind of data source as long as the source returns a collection.

You can easily bind a control to a factory object by using the BindingSource control.

Example

The following example demonstrates how to bind a DataGridView control to a factory method by using a BindingSource control. The factory method is named GetOrdersByCustomerId, and it returns all the orders for a given customer in the Northwind database.

Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Data.Common
Imports System.Diagnostics
Imports System.Drawing
Imports System.Data.SqlClient
Imports System.Windows.Forms

' This form demonstrates using a BindingSource to bind to a factory
' object. 

Public Class Form1
    Inherits System.Windows.Forms.Form
    ' This is the TextBox for entering CustomerID values.
    Private WithEvents customerIdTextBox As New TextBox()

    ' This is the DataGridView that displays orders for the 
    ' specified customer.
    Private customersDataGridView As New DataGridView()

    ' This is the BindingSource for binding the database query
    ' result set to the DataGridView.
    Private ordersBindingSource As New BindingSource()

    Public Sub New() 

        ' Set up the CustomerID TextBox.
        Me.customerIdTextBox.Location = New Point(100, 200)
        Me.customerIdTextBox.Size = New Size(500, 30)
        Me.customerIdTextBox.Text = _
            "Enter a valid Northwind CustomerID, for example: ALFKI," & _
            " then RETURN or click outside the TextBox"
        Me.Controls.Add(Me.customerIdTextBox)

        ' Set up the DataGridView.
        customersDataGridView.Dock = DockStyle.Top
        Me.Controls.Add(customersDataGridView)

        ' Set up the form.
        Me.Size = New Size(800, 500)
    End Sub

    ' This event handler binds the BindingSource to the DataGridView
    ' control's DataSource property.
    Private Sub Form1_Load(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Me.Load

        ' Attach the BindingSource to the DataGridView.
        Me.customersDataGridView.DataSource = Me.ordersBindingSource

    End Sub

    ' This is a static factory method. It queries the Northwind 
    ' database for the orders belonging to the specified
    ' customer and returns an IEnumerable.
    Public Shared Function GetOrdersByCustomerId(ByVal id As String) _
        As IEnumerable

        ' Open a connection to the database.
        Dim connectString As String = "Integrated Security=SSPI;" & _
             "Persist Security Info=False;Initial Catalog=Northwind;" & _
             "Data Source= localhost"
        Dim connection As New SqlConnection()

        connection.ConnectionString = connectString
        connection.Open()

        ' Execute the query.
        Dim queryString As String = _
            String.Format("Select * From Orders where CustomerID = '{0}'", id)
        Dim command As New SqlCommand(queryString, connection)
        Dim reader As SqlDataReader = _
            command.ExecuteReader(CommandBehavior.CloseConnection)
        Return reader

    End Function

    ' These event handlers are called when the user tabs or clicks
    ' out of the customerIdTextBox or hits the return key.
    ' The database is then queried with the CustomerID
    '  in the customerIdTextBox.Text property.
    Private Sub customerIdTextBox_Leave(ByVal sender As Object, _
        ByVal e As EventArgs) Handles customerIdTextBox.Leave

        ' Attach the data source to the BindingSource control.
        Me.ordersBindingSource.DataSource = _
            GetOrdersByCustomerId(Me.customerIdTextBox.Text)

    End Sub


    Private Sub customerIdTextBox_KeyDown(ByVal sender As Object, _
        ByVal e As KeyEventArgs) Handles customerIdTextBox.KeyDown

        If e.KeyCode = Keys.Return Then

            ' Attach the data source to the BindingSource control.
            Me.ordersBindingSource.DataSource = _
                GetOrdersByCustomerId(Me.customerIdTextBox.Text)
        End If

    End Sub

    <STAThread()> _
    Shared Sub Main()
        Application.EnableVisualStyles()
        Application.Run(New Form1())

    End Sub
End Class

Compiling the Code

This example requires:

  • References to the System, System.Data, System.Drawing and System.Windows.Forms assemblies.

For information about building this example from the command line for Visual Basic or Visual C#, see Building from the Command Line (Visual Basic) or Command-line Building With csc.exe. You can also build this example in Visual Studio by pasting the code into a new project. Also see How to: Compile and Run a Complete Windows Forms Code Example Using Visual Studio.

Show: