Partager via


How to: Populate documents with data from services

Applies to: yesVisual Studio noVisual Studio for Mac

Note

This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

Data access works the same way in document-level projects for Microsoft Office as it does in Windows Forms projects. You use the same tools and code to bring the data into your solution, and you can even use Windows Forms controls to display the data. In addition, you can take advantage of controls called host controls, which are native objects in Microsoft Office Excel and Microsoft Office Word that have been enhanced with events and data binding capability. For more information, see Host items and host controls overview.

Applies to: The information in this topic applies to document-level projects for Excel and Word. For more information, see Features available by Office application and project type.

The following example shows how to add data-bound controls to documents at design time. For an example of how to add data-bound controls in VSTO Add-ins at run time, see Walkthrough: Bind to data from a service in a VSTO Add-in project.

To populate a document-level project with data from a web service

  1. Open the Data Sources window and create a service data source for your project. For more information, see Add new data sources.

  2. Drag the table or field you want from the Data Sources window to your document.

    A control is created on the document, a BindingSource is created that is bound to the object class in your project, and classes are generated for the service.

  3. In your code, create an instance of the web service class that you connected to in step 1.

  4. If there are properties that are required for communication with the web service, create instances of those properties.

  5. Create and send a data request using methods exposed by the Web service and any property instances you created in step 4.

    The methods that you use depend on what the web service offers.

  6. Assign the data response from the web service to the DataSource property of the BindingSource.

When you run the project, the controls display the first record in the data source. You can enable scrolling through the records by handling the currency events using the objects in the BindingSource.

See also