Dela via


Object Binding in Visual Studio

Visual Studio provides design-time tools for working with custom objects (as opposed to datasets and Web services) as the data source in your application.

The only requirement for custom objects to work with the data design tools in Visual Studio is that the object needs at least one public property. No specific constructors or attributes are required for custom objects to work with tools such as the Data Sources window.

While there are countless ways to implement your application logic when working with objects as a data source, there are a few standard operations that can be simplified by using the new Visual Studio–generated TableAdapter objects. This page explains how to implement these standard processes using TableAdapters; it is not intended as a guide for creating your custom objects. For example, you will typically perform the following standard operations regardless of the specific implementation of your objects, or application's logic:

  • Loading data into objects (typically from a database)

  • Creating a typed collection of objects

  • Adding objects to and removing objects from a collection

  • Displaying the object data to users on a form

  • Changing/editing the data in an object

  • Saving data from objects back to the database

Note

In order to better understand, and provide context for the examples on this page, we suggest that you complete the following: Walkthrough: Connecting to Data in Objects. That walkthrough creates the objects discussed on this Help page.

Loading Data into Objects

For this example, you load data into your objects using TableAdapters. By default, TableAdapters are created with two kinds of methods that fetch data from a database and populate data tables.

  • The TableAdapter.Fill method fills an existing data table with the data returned.

  • The TableAdapter.GetData method returns a new data table populated with data.

The easiest way to load your custom objects with data is to call the TableAdapter.GetData method, loop through the collection of rows in the returned data table, and populate each object with the values in each row. You can create a GetData method that returns a populated data table for any query added to a TableAdapter.

Note

Visual Studio names the TableAdapter queries Fill and GetData by default, but those names can be changed to any valid method name.

The following example shows how to loop through the rows in a data table and populate an object with data:

For a complete code example, see Walkthrough: Connecting to Data in Objects.

Private Sub LoadCustomers()
    Dim customerData As NorthwindDataSet.CustomersDataTable = _
        CustomersTableAdapter1.GetTop5Customers()

    Dim customerRow As NorthwindDataSet.CustomersRow

    For Each customerRow In customerData
        Dim currentCustomer As New Customer()
        With currentCustomer

            .CustomerID = customerRow.CustomerID
            .CompanyName = customerRow.CompanyName

            If Not customerRow.IsAddressNull Then
                .Address = customerRow.Address
            End If 

            If Not customerRow.IsCityNull Then
                .City = customerRow.City
            End If 

            If Not customerRow.IsContactNameNull Then
                .ContactName = customerRow.ContactName
            End If 

            If Not customerRow.IsContactTitleNull Then
                .ContactTitle = customerRow.ContactTitle
            End If 

            If Not customerRow.IsCountryNull Then
                .Country = customerRow.Country
            End If 

            If Not customerRow.IsFaxNull Then
                .Fax = customerRow.Fax
            End If 

            If Not customerRow.IsPhoneNull Then
                .Phone = customerRow.Phone
            End If 

            If Not customerRow.IsPostalCodeNull Then
                .PostalCode = customerRow.PostalCode
            End If 

            If Not customerRow.Is_RegionNull Then
                .Region = customerRow._Region
            End If 

        End With

        LoadOrders(currentCustomer)
        CustomerBindingSource.Add(currentCustomer)
    Next 
End Sub
private void LoadCustomers()
{
    NorthwindDataSet.CustomersDataTable customerData = 
        customersTableAdapter1.GetTop5Customers();

    foreach (NorthwindDataSet.CustomersRow customerRow in customerData)
    {
        Customer currentCustomer = new Customer();
        currentCustomer.CustomerID = customerRow.CustomerID;
        currentCustomer.CompanyName = customerRow.CompanyName;

        if (customerRow.IsAddressNull() == false)
        {
            currentCustomer.Address = customerRow.Address;
        }

        if (customerRow.IsCityNull() == false)
        {
            currentCustomer.City = customerRow.City;
        }

        if (customerRow.IsContactNameNull() == false)
        {
            currentCustomer.ContactName = customerRow.ContactName;
        }

        if (customerRow.IsContactTitleNull() == false)
        {
            currentCustomer.ContactTitle = customerRow.ContactTitle;
        }

        if (customerRow.IsCountryNull() == false)
        {
            currentCustomer.Country = customerRow.Country;
        }

        if (customerRow.IsFaxNull() == false)
        {
            currentCustomer.Fax = customerRow.Fax;
        }

        if (customerRow.IsPhoneNull() == false)
        {
            currentCustomer.Phone = customerRow.Phone;
        }

        if (customerRow.IsPostalCodeNull() == false)
        {
            currentCustomer.PostalCode = customerRow.PostalCode;
        }

        if (customerRow.IsRegionNull() == false)
        {
            currentCustomer.Region = customerRow.Region;
        }

        LoadOrders(currentCustomer);
        customerBindingSource.Add(currentCustomer);
    }
}

Creating a Typed Collection of Objects

You can create collection classes for your objects or use the typed collections that are automatically provided by the BindingSource Component.

When you are creating a custom collection class for objects, we suggest that you inherit from BindingList<T>. This generic class provides functionality to administer your collection, as well as the ability to raise events that send notifications to the data-binding infrastructure in Windows Forms.

The automatically-generated collection in the BindingSource uses a BindingList<T> for its typed collection. If your application does not require additional functionality, then you can maintain your collection within the BindingSource. For more information, see the List property of the BindingSource class.

Note

If your collection will require functionality not provided by the base implementation of the BindingList<T>, then you should create a custom collection so you can add to the class as needed.

The following code shows how to create the class for a strongly-typed collection of Order objects:

''' <summary> 
''' A collection of Orders 
''' </summary> 
Public Class Orders
    Inherits System.ComponentModel.BindingList(Of Order)

    ' Add any additional functionality required by your collection. 

End Class
/// <summary> 
/// A collection of Orders 
/// </summary> 
public class Orders: System.ComponentModel.BindingList<Order>
{
    // Add any additional functionality required by your collection.
}

Adding Objects to a Collection

You add objects to a collection by calling the Add method of your custom collection class or of the BindingSource.

For an example of adding to a collection using a BindingSource, see the LoadCustomers method in Walkthrough: Connecting to Data in Objects.

For an example of adding objects to a custom collection, see the LoadOrders method in Walkthrough: Connecting to Data in Objects.

Note

The Add method is automatically provided for your custom collection when you inherit from BindingList<T>.

The following code shows how to add objects to the typed collection in a BindingSource:

Dim currentCustomer As New Customer()
CustomerBindingSource.Add(currentCustomer)
Customer currentCustomer = new Customer();
customerBindingSource.Add(currentCustomer);

The following code shows how to add objects to a typed collection that inherits from BindingList<T>:

Note

In this example the Orders collection is a property of the Customer object.

Dim currentOrder As New Order()
currentCustomer.Orders.Add(currentOrder)
Order currentOrder = new Order();
currentCustomer.Orders.Add(currentOrder);

Removing Objects from a Collection

You remove objects from a collection by calling the Remove or RemoveAt method of your custom collection class or of BindingSource.

Note

The Remove and RemoveAt methods are automatically provided for your custom collection when you inherit from BindingList<T>.

The following code shows how to locate and remove objects from the typed collection in a BindingSource with the RemoveAt method:

Dim customerIndex As Integer = CustomerBindingSource.Find("CustomerID", "ALFKI")
CustomerBindingSource.RemoveAt(customerIndex)
int customerIndex = customerBindingSource.Find("CustomerID", "ALFKI");
customerBindingSource.RemoveAt(customerIndex);

Displaying Object Data to Users

To display the data in objects to users, you create an object data source using the Data Source Configuration Wizard, and then drag the entire object or individual properties onto your form from the Data Sources window.

For more information on creating an object data source, see How to: Connect to Data in an Object.

For more information on displaying data from objects on Windows Forms, see Displaying Data on Forms in Windows Applications.

Modifying the Data in Objects

To edit data in custom objects that are data-bound to Windows Forms controls, simply edit the data in the bound control (or directly in the object's properties). Data-binding architecture will update the data in the object.

If your application requires the tracking of changes and the rolling back of proposed changes to their original values, then you must implement this functionality in your object model. For examples of how data tables keep track of proposed changes, see DataRowState, HasChanges, and GetChanges.

Saving Data in Objects Back to the Database

You save data back to the database by passing the values from your object to the TableAdapter's DBDirect methods.

Visual Studio creates DBDirect methods that can be executed directly against the database. These methods do not require DataSet or DataTable objects.

TableAdapter DBDirect method

Description

TableAdapter.Insert

Adds new records to a database, allowing you to pass in individual column values as method parameters.

TableAdapter.Update

Updates existing records in a database. The Update method takes original and new column values as method parameters. The original values are used to locate the original record, and the new values are used to update that record.

The TableAdapter.Update method is also used to reconcile changes in a dataset back to the database by taking a DataSet, DataTable, DataRow, or array of DataRows as method parameters.

TableAdapter.Delete

Deletes existing records from the database based on the original column values passed in as method parameters.

To save data from a collection of objects, loop through the collection of objects (for example, using a for-next loop) and send the values for each object to the database using the TableAdapter's DBDirect methods.

The following example shows how to use the TableAdapter.Insert DBDirect method to add a new customer directly into the database:

Private Sub AddNewCustomer(ByVal currentCustomer As Customer)

    CustomersTableAdapter.Insert( _
        currentCustomer.CustomerID, _
        currentCustomer.CompanyName, _
        currentCustomer.ContactName, _
        currentCustomer.ContactTitle, _
        currentCustomer.Address, _
        currentCustomer.City, _
        currentCustomer.Region, _
        currentCustomer.PostalCode, _
        currentCustomer.Country, _
        currentCustomer.Phone, _
        currentCustomer.Fax)
End Sub
private void AddNewCustomers(Customer currentCustomer)
{
    customersTableAdapter.Insert( 
        currentCustomer.CustomerID, 
        currentCustomer.CompanyName, 
        currentCustomer.ContactName, 
        currentCustomer.ContactTitle, 
        currentCustomer.Address, 
        currentCustomer.City, 
        currentCustomer.Region, 
        currentCustomer.PostalCode, 
        currentCustomer.Country, 
        currentCustomer.Phone, 
        currentCustomer.Fax);
}

See Also

Tasks

How to: Connect to Data in an Object

Walkthrough: Connecting to Data in Objects

How to: Save Data from an Object to a Database

How to: Directly Access the Database with a TableAdapter

Walkthrough: Saving Data with the TableAdapter DBDirect Methods

Other Resources

Displaying Data on Forms in Windows Applications

TableAdapters

Saving Data