Freigeben über


Walkthrough: Connecting to Data in a Web Service (Windows Forms)

This walkthrough shows how to connect your application to a web service using the Data Source Configuration Wizard. You will connect to the Live Search web service and run search queries from your application. The data returned by the service (the search results) will be displayed on a Windows Form.

Tasks illustrated in this walkthrough include:

  • Creating a new Windows Application project.

  • Adding a Service Reference to an application (connect to the Live Search service.)

  • Adding controls to run search queries (call methods exposed by the service).

  • Writing code to access the service and return data.

  • Binding the data returned from the service to the BindingSource.

  • Display the data returned from the service in a grid.

Obtaining an AppID

An AppID from Live Search is available for free, and uniquely identifies your application to the Live Search service. The AppID is required to access the service.

To obtain an AppID

  • Navigate to http://search.live.com/developer and get a free AppID

    Note

    It might take some time (30-60 minutes) for the AppID to validate with the service. If you encounter a generic 'Client Error' within this time when running the application it is likely that the AppID is still in the process of being enabled on the Live Search servers.

Creating the Project

To create the new project

  1. From the File menu, create a new project.

  2. Select Windows Forms Application and name it WebServiceWalkthrough.

  3. Click OK.

    The project is created and added to Solution Explorer.

Connecting to the Service

Connect to the web service by running the Data Source Configuration Wizard.

To connect to the Live Search web service

  1. On the Data menu, click Show Data Sources.

  2. In the Data Sources window, select Add New Data Source.

  3. Select Service on the Choose a Data Source Type page, and click Next.

  4. Type https://soap.search.msn.com/webservices.asmx?wsdl in the URL box of the Add Service Reference dialog box.

  5. Click Go.

  6. After the Web service is found, change the Namespace to: LiveSearchService.

  7. Click OK, and then click Finish to add the service reference to your project.

    The service reference is added to the project, and the Data Sources window is populated based on the items returned by the service.

Note

Because different web services expose different functionality, the next steps in this walkthrough are specific to consuming the Live Search web service. The typical process for consuming data from a service is to create an instance of the service, and then call methods exposed by the service. After dragging items from the Data Sources window your form should contain a BindingSource component; set the DataSource property to the data returned by the service.

Creating a DataGridView to Display Data Returned by the Service

Create a data-bound data grid by dragging items from the Data Sources window onto the form. After adding the grid, configure the columns to display only the columns we want to present. Then set the Url column to a link so users can click the url and navigate to the web sites returned by the search query.

To create the data-bound DataGridView

  1. Expand the SearchResponse node in the Data Sources window.

  2. Expand the Responses node.

  3. Drag the Results node onto the form.

    A DataGridView, BindingSource, and BindingNavigator are added to the form.

  4. Select the resultsDataGridView that was added to the form.

  5. In the Properties window select the Columns property and click the ellipses (…) to open the Edit Columns Dialog Box (Design view).

  6. Select the Url column and set the:

    1. ColumnType property to DataGridViewLinkColumn.

    2. AutoSizeMode property to AllCells.

  7. Remove all columns except for the Title, Description, and Url columns.

  8. Click OK.

Adding Controls for Entering Search Criteria and Running the Search Query

Add controls to the existing tool strip for running search queries.

To add a text box and button to the form

  1. Right click the grayed disk icon on the form's tool strip and select Insert followed by TextBox.

  2. In the Properties window, set the Name property to searchCriteriaTextBox.

  3. Set the Text property to Visual Studio.

  4. Add a Button to the toolstrip and name it searchButton.

  5. In the Properties window, set the DisplayStyle property to Text.

  6. Set the Text property to Search.

Creating an Event Handler to Open the Web Site Clicked in the Grid

Add an event handler for the CellContentClick event.

To create the CellContentClick Event Handler

  1. Select the resultsDataGridView on the form and click the Events button in the Properties window. The Events button is the button with the lightning bolt icon.

  2. Double click the CellContentClick event to create and navigate to the handler stub.

  3. Add code to check which column was clicked and to navigate to the web page if the Url column is clicked:

    Private Sub ResultsDataGridView_CellContentClick( _
        ByVal sender As System.Object, _
        ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) _
        Handles ResultsDataGridView.CellContentClick
    
        ' When the content in a cell is clicked check to see if it is the Url column. 
        ' If it is, pass the url to the Process.Start method to open the web page. 
        If ResultsDataGridView.Columns(e.ColumnIndex).DataPropertyName = "Url" Then
            System.Diagnostics.Process.Start(ResultsDataGridView.SelectedCells(0).Value)
        End If 
    End Sub
    
    private void resultsDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        // When the content in a cell is clicked check to see if it is the Url column. 
        // If it is, pass the url to the Process.Start method to open the web page. 
        if (resultsDataGridView.Columns[e.ColumnIndex].DataPropertyName == "Url")
        {
            System.Diagnostics.Process.Start(resultsDataGridView.SelectedCells[0].Value.ToString());
        }
    }
    

Adding Code to Access the Live Search Service and Run a Search Query

Access the service by instantiating an instance of the service in your application and calling the methods exposed by the service.

To access and consume the service

  1. Open Form1 in the code editor.

  2. Add the following method to Form1:

    Private Sub RunSearchRequest()
    
        ' Create an instance of the service. 
        Dim searchService As New LiveSearchService.MSNSearchPortTypeClient
    
        ' Instantiate a new SearchRequest. 
        Dim searchRequest As New LiveSearchService.SearchRequest
    
        ' Create a new SourceRequest. 
        Dim sourceRequest(1) As LiveSearchService.SourceRequest
        sourceRequest(0) = New LiveSearchService.SourceRequest
    
        ' To search the web, set the SourceType to Web.
        sourceRequest(0).Source = LiveSearchService.SourceType.Web
    
        ' Set the columns you want the query to return.
        sourceRequest(0).ResultFields = _
            LiveSearchService.ResultFieldMask.Description And _
            LiveSearchService.ResultFieldMask.Url And _
            LiveSearchService.ResultFieldMask.Title
    
        ' Search for the text in the textbox.
        searchRequest.Query = searchCriteriaTextBox.Text
    
        ' Set the SearchRequest to the SourceRequest array.
        searchRequest.Requests = sourceRequest
    
    
        ' Replace with a valid AppID. Obtain a free AppID at: 
        ' http://search.live.com/developer 
        searchRequest.AppID = "AppID"
        searchRequest.CultureInfo = "en-US" 
    
        ' Create a SearchResponse, then call the Search method 
        ' and assign the return value to the response object. 
        Dim searchResponse As LiveSearchService.SearchResponse = _
            searchService.Search(searchRequest)
    
        ' Bind the results to the form's BindingSource.
        ResultsBindingSource.DataSource = searchResponse.Responses(0).Results
    End Sub
    
    private void RunSearchRequest()
    {
        // Create an instance of the service.
        LiveSearchService.MSNSearchPortTypeClient searchService =
            new LiveSearchService.MSNSearchPortTypeClient();
    
        // Instantiate a new search request.
        LiveSearchService.SearchRequest searchRequest = new LiveSearchService.SearchRequest();
    
        // Create a new SourceRequest.
        LiveSearchService.SourceRequest[] sourceRequest = new LiveSearchService.SourceRequest[1];
        sourceRequest[0] = new LiveSearchService.SourceRequest();
    
        // Set the number of results to return.
        sourceRequest[0].Count = 7;
    
        // To search the web, set the SourceType to Web.
        sourceRequest[0].Source = LiveSearchService.SourceType.Web;
    
        // Set the columns to be returned from the search query.
        sourceRequest[0].ResultFields = LiveSearchService.ResultFieldMask.Description |
            LiveSearchService.ResultFieldMask.Url |
            LiveSearchService.ResultFieldMask.Title;
    
        // Set the search query to the value in the text box.
        searchRequest.Query = searchCriteriaTextBox.Text;
    
        // Set the search request to the array of source requests.
        searchRequest.Requests = sourceRequest;
    
        // Replace with a valid AppID. Obtain a free AppID at: 
        // http://search.live.com/developer 
        searchRequest.AppID = "AppID";
        searchRequest.CultureInfo = "en-US";
    
        // Create a SearchResponse, then call the search method 
        // and assign the return value to the response object.
        LiveSearchService.SearchResponse searchResponse = searchService.Search(searchRequest);
    
        // Bind the results from the search query to the form's BindingSource.
        resultsBindingSource.DataSource = searchResponse.Responses[0].Results;
    }
    

Note

Be sure to replace searchRequest.AppID = "AppID" with the AppID value obtained from the Live Search service.

Creating an Event Handler to Run a Search when the Search Button is Clicked

Create an event handler for the searchButton.Click event and call the RunSearchRequest method.

To implement searching when the button is clicked

  1. Open Form1 in design view.

  2. Double click the Search button.

  3. Add the following line of code in the generated handler:

    Private Sub searchButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles searchButton.Click
        RunSearchRequest()
    End Sub
    
    private void searchButton_Click(object sender, EventArgs e)
    {
        RunSearchRequest();
    }
    

Running the Application

Run the application and perform a search.

  1. Run the application (press F5).

  2. Click Search to search the web for Visual Studio, the default text in the searchCriteriaTextBox.

    The Grid displays the first ten search results.

  3. Click one of the Urls to navigate to that web site.

  4. Type Redmond WA Weather in the text box and click Search.

    The grid updates with the new search results.

Next Steps

Accessing the Live Search service is meant only as a starting point to understand how to display the data returned from a service utilizing the data binding features in Windows Forms applications. After connecting to a different service, and after dragging items from the Data Sources window your form should contain a BindingSource component; set the DataSource property to the data returned by the service. For more information, see BindingSource Component Overview.

Note

The items that appear in the Data Sources window are dependent on the information that the Web service returns. Some Web services might not provide enough information for the Data Source Configuration Wizard to create bindable objects. For example, if the Web service returns an object that does not provide any discoverable schema, then no items will appear in the Data Sources window upon completing the wizard.

To add functionality to your application

See Also

Concepts

Binding Controls to Data in Visual Studio

Editing Data in Your Application

Validating Data

Saving Data

Other Resources

Data Walkthroughs