Data Access has been discontinued. Please refer to this page for more information.

How to: Add an Object as a Project Data Source

You can create data sources that are based on your objects in a Visual Studio application. After you have defined a data type as a data source in a project, you can create forms that display model data by dragging items from the Data Sources window onto forms. These items become controls on the form that are bound to the data source.

In this topic, you will create a data source for the Category type in the SofiaCarRental database. You will then use this data source to create a Windows Form with controls that are bound to data. To complete these procedures, you must have already added the Northwind model to your project.

To create a data source based on the Category type:

  1. Create a new SofiaCarRental model.
  2. Build your project
  3. On the Data menu, click Add New Data Source (In Visual Studio 2012, use the Project -> Add New Data Source menu command) .
  4. On the Choose a Data Source Type page, select Object.
  5. On the Select an Object You Wish to Bind to page, expand the project node, expand the project's namespace node, and select the Category type in the tree view.
  6. Click Finish. The Category data source is added to the Data Sources (View -> Other Widnows -> Show Data Sources) window.

To add data source bound controls to a Windows Form:

  1. In the Data Sources window, expand the Category node.
  2. Drag the Category node to the form. This creates the categoriesBindingSource and categoriesBindingSourceNavigator controls on the form. A categoriesDataGridView is added to the form, too.

To bind the data source to the result of a LINQ query:

  1. In the code-behind, add the following code that creates an OpenAccessContext instance.

    private FluentModel dbContext = new FluentModel();
    
    Private dbContext As New FluentModel()
    
  2. Attach to the Load event of the form.

  3. In the Load event handler, add the following code.

    private void Form1_Load(object sender, System.EventArgs e)
    {
       categoryBindingSource.DataSource = dbContext.Categories.ToList();
    }
    
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
     categoryBindingSource.DataSource = dbContext.Categories.ToList()
    End Sub
    

See Also