共用方式為


HOW TO:使用 Windows Form BindingSource 繫結至 Web 服務

更新:2007 年 11 月

如果想要將 Windows Form 控制項繫結至呼叫 XML Web Service 所得到的結果,可以使用 BindingSource 元件。這個程序和將 BindingSource 元件繫結至型別很類似。您必須建立用戶端 Proxy,這個 Proxy 要包含 Web 服務所公開 (Expose) 的方法和型別。用戶端 Proxy 可以由 Web 服務 (.asmx) 自己產生,或者由它的 Web 服務描述語言 (WSDL) 檔產生。此外,用戶端 Proxy 必須公開 Web 服務當做公用屬性使用的複雜型別的欄位。然後將 BindingSource 繫結至 Web 服務 Proxy 中所公開的其中一個型別。

若要建立並繫結至用戶端 Proxy

  1. 請使用適當的命名空間 (Namespace),在選擇的目錄中建立 Windows Form。

  2. 在表單中加入 BindingSource 元件。

  3. 開啟 Windows Software Development Kit (SDK) 命令提示字元,並且巡覽至表單所在的目錄。

  4. 使用 WSDL 工具,輸入 wsdl 以及 Web 服務 .asmx 或 WSDL 檔的 URL,接著再輸入應用程式的命名空間,而且還可以選擇您要使用的語言。

    下列程式碼範例使用的 Web 服務位於 http://webservices.eraserver.net/zipcoderesolver/zipcoderesolver.asmx。例如,如果是 C#,請輸入 wsdl http://webservices.eraserver.net.zipcoderesolver/zipcoderesolver.asmx /n:BindToWebService,如果是 Visual Basic,則請輸入 wsdl http://webservices.eraserver.net.zipcoderesolver/zipcoderesolver.asmx /n:BindToWebService /language:VB。將路徑當做引數傳遞至 WSDL 工具,將會以指定的語言在與應用程式相同的目錄和命名空間中產生用戶端 Proxy。如果您使用的是 Visual Studio,請將檔案加入至專案。

  5. 選取用戶端 Proxy 中要繫結至的型別。

    這個型別通常是 Web 服務所提供的方法傳回的型別。所選擇的型別其欄位必須公開為供繫結使用的公用屬性。

    <System.SerializableAttribute(), _
     System.Xml.Serialization.XmlTypeAttribute( _
        [Namespace]:="http://webservices.eraserver.net/")> _
    Public Class USPSAddress
    
        Private streetField As String
    
        Private cityField As String
    
        Private stateField As String
    
        Private shortZIPField As String
    
        Private fullZIPField As String
    
    
        Public Property Street() As String
            Get
                Return Me.streetField
            End Get
            Set(ByVal value As String)
                Me.streetField = value
            End Set
        End Property
    
    
        Public Property City() As String
            Get
                Return Me.cityField
            End Get
            Set(ByVal value As String)
                Me.cityField = value
            End Set
        End Property
    
        Public Property State() As String
            Get
                Return Me.stateField
            End Get
            Set(ByVal value As String)
                Me.stateField = value
            End Set
        End Property
    
    
        Public Property ShortZIP() As String
            Get
                Return Me.shortZIPField
            End Get
            Set(ByVal value As String)
                Me.shortZIPField = value
            End Set
        End Property
    
    
        Public Property FullZIP() As String
            Get
                Return Me.fullZIPField
            End Get
            Set(ByVal value As String)
                Me.fullZIPField = value
            End Set
        End Property
    End Class
    
     [System.SerializableAttribute, System.Xml.Serialization.XmlTypeAttribute(
            Namespace="http://webservices.eraserver.net/")]
        public class USPSAddress
        {
    
            private string streetField;
    
            private string cityField;
    
            private string stateField;
    
            private string shortZIPField;
    
            private string fullZIPField;
    
    
            public string Street    
            {
                get
                {
                    return this.streetField;
                }
                set
                {
                    this.streetField = value;
                }
            }
    
    
            public string City    
            {
                get
                {
                    return this.cityField;
                }
                set
                {
                    this.cityField = value;
                }
            }
    
            public string State    
            {
                get
                {
                    return this.stateField;
                }
                set
                {
                    this.stateField = value;
                }
            }
    
    
            public string ShortZIP    
            {
                get
                {
                    return this.shortZIPField;
                }
                set
                {
                    this.shortZIPField = value;
                }
            }
    
    
            public string FullZIP    
            {
                get
                {
                    return this.fullZIPField;
                }
                set
                {
                    this.fullZIPField = value;
                }
            }
        }
    
        [System::SerializableAttribute, System::Xml::Serialization::XmlTypeAttribute(
            Namespace="http://webservices.eraserver.net/")]
        public ref class USPSAddress
        {
    
    private:
            String^ streetField;
    
            String^ cityField;
    
            String^ stateField;
    
            String^ shortZIPField;
    
            String^ fullZIPField;
    
    
    public:
            property String^ Street    
            {
                String^ get()
                {
                    return this->streetField;
                }
                void set( String^ value )
                {
                    this->streetField = value;
                }
            }
    
    
            property String^ City    
            {
                String^ get()
                {
                    return this->cityField;
                }
                void set( String^ value )
                {
                    this->cityField = value;
                }
            }
            property String^ State    
            {
                String^ get()
                {
                    return this->stateField;
                }
                void set( String^ value )
                {
                    this->stateField = value;
                }
            }
    
            property String^ ShortZIP    
            {
                String^ get()
                {
                    return this->shortZIPField;
                }
                void set( String^ value )
                {
                    this->shortZIPField = value;
                }
            }
    
            property String^ FullZIP    
            {
                String^ get()
                {
                    return this->fullZIPField;
                }
                void set( String^ value )
                {
                    this->fullZIPField = value;
                }
            }
        };
    
  6. BindingSourceDataSource 屬性設定為所需的型別,此型別必須是 Web 服務用戶端 Proxy 中所包含的型別。

    BindingSource1.DataSource = GetType(USPSAddress)
    
             BindingSource1.DataSource = typeof(USPSAddress);
    
                BindingSource1->DataSource = USPSAddress::typeid;
    

若要將控制項繫結至已繫結於 Web 服務的 BindingSource

  • 將控制項繫結至 BindingSource,並將所需之 Web 服務類型的公用屬性當做參數傳遞。

    textBox1.DataBindings.Add("Text", Me.BindingSource1, "FullZIP", True)
    
             textBox1.DataBindings.Add("Text", this.BindingSource1, "FullZIP", true);
    
                textBox1->DataBindings->Add("Text", this->BindingSource1, "FullZIP", true);
    

範例

下列程式碼範例會先示範如何將 BindingSource 元件繫結至 Web 服務,然後再示範如何將文字方塊繫結至 BindingSource 元件。當您一下按鈕時,Web 服務的方法會被呼叫,而結果將顯示於 textbox1。

Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Drawing
Imports System.Windows.Forms

Namespace BindToWebService
    Class Form1
        Inherits Form

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

        Private BindingSource1 As New BindingSource()
        Private textBox1 As New TextBox()
        Private textBox2 As New TextBox()
        Private WithEvents button1 As New Button()

        Public Sub New()

            textBox1.Location = New System.Drawing.Point(118, 131)
            textBox1.ReadOnly = True
            button1.Location = New System.Drawing.Point(133, 60)
            button1.Text = "Get zipcode"
            ClientSize = New System.Drawing.Size(292, 266)
            Controls.Add(Me.button1)
            Controls.Add(Me.textBox1)
        End Sub

        Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) _
            Handles button1.Click

            textBox1.Text = "Calling Web service.."
            Dim resolver As New ZipCodeResolver()
            BindingSource1.Add(resolver.CorrectedAddressXml("0", "One Microsoft Way", "Redmond", "WA"))

        End Sub


        Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
            BindingSource1.DataSource = GetType(USPSAddress)
            textBox1.DataBindings.Add("Text", Me.BindingSource1, "FullZIP", True)
        End Sub

    End Class

    <System.Diagnostics.DebuggerStepThroughAttribute(), _
     System.ComponentModel.DesignerCategoryAttribute("code"), _
     System.Web.Services.WebServiceBindingAttribute(Name:="ZipCodeResolverSoap", _
        [Namespace]:="http://webservices.eraserver.net/")> _
    Public Class ZipCodeResolver
        Inherits System.Web.Services.Protocols.SoapHttpClientProtocol

        Private CorrectedAddressXmlOperationCompleted As _
            System.Threading.SendOrPostCallback


        Public Sub New()
            MyBase.New()
            Me.Url = _
                "http://webservices.eraserver.net/zipcoderesolver/zipcoderesolver.asmx"
        End Sub


        Public Event CorrectedAddressXmlCompleted As _
            CorrectedAddressXmlCompletedEventHandler

        <System.Web.Services.Protocols.SoapDocumentMethodAttribute( _
            "http://webservices.eraserver.net/CorrectedAddressXml", _
            RequestNamespace:="http://webservices.eraserver.net/", _
            ResponseNamespace:="http://webservices.eraserver.net/", _
            Use:=System.Web.Services.Description.SoapBindingUse.Literal, _
            ParameterStyle:=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)> _
        Public Function CorrectedAddressXml(ByVal accessCode As String, _
            ByVal address As String, ByVal city As String, ByVal state As String) _
            As USPSAddress
            Dim results() As Object = Me.Invoke("CorrectedAddressXml", _
                New Object() {accessCode, address, city, state})
            Return CType(results(0), USPSAddress)
        End Function

        '''<remarks/>
        Public Function BeginCorrectedAddressXml(ByVal accessCode As String, _
            ByVal address As String, ByVal city As String, ByVal state As String, _
            ByVal callback As System.AsyncCallback, ByVal asyncState As Object) _
            As System.IAsyncResult

            Return Me.BeginInvoke("CorrectedAddressXml", _
                New Object() {accessCode, address, city, state}, callback, asyncState)
        End Function

        Public Function EndCorrectedAddressXml(ByVal asyncResult _
            As System.IAsyncResult) As USPSAddress
            Dim results() As Object = Me.EndInvoke(asyncResult)
            Return CType(results(0), USPSAddress)
        End Function
    End Class

    <System.SerializableAttribute(), _
     System.Xml.Serialization.XmlTypeAttribute( _
        [Namespace]:="http://webservices.eraserver.net/")> _
    Public Class USPSAddress

        Private streetField As String

        Private cityField As String

        Private stateField As String

        Private shortZIPField As String

        Private fullZIPField As String


        Public Property Street() As String
            Get
                Return Me.streetField
            End Get
            Set(ByVal value As String)
                Me.streetField = value
            End Set
        End Property


        Public Property City() As String
            Get
                Return Me.cityField
            End Get
            Set(ByVal value As String)
                Me.cityField = value
            End Set
        End Property

        Public Property State() As String
            Get
                Return Me.stateField
            End Get
            Set(ByVal value As String)
                Me.stateField = value
            End Set
        End Property


        Public Property ShortZIP() As String
            Get
                Return Me.shortZIPField
            End Get
            Set(ByVal value As String)
                Me.shortZIPField = value
            End Set
        End Property


        Public Property FullZIP() As String
            Get
                Return Me.fullZIPField
            End Get
            Set(ByVal value As String)
                Me.fullZIPField = value
            End Set
        End Property
    End Class

    Public Delegate Sub CorrectedAddressXmlCompletedEventHandler(ByVal sender As Object, _
         ByVal args As CorrectedAddressXmlCompletedEventArgs)

    Public Class CorrectedAddressXmlCompletedEventArgs
        Inherits System.ComponentModel.AsyncCompletedEventArgs

        Private results() As Object

        Friend Sub New(ByVal results() As Object, ByVal exception As System.Exception, _
            ByVal cancelled As Boolean, ByVal userState As Object)
            MyBase.New(exception, cancelled, userState)
            Me.results = results
        End Sub

        Public ReadOnly Property Result() As USPSAddress
            Get
                Me.RaiseExceptionIfNecessary()
                Return CType(Me.results(0), USPSAddress)
            End Get
        End Property
    End Class

End Namespace
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace BindToWebService {
    class Form1: Form

    {
        [STAThread]
        public static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }

        private BindingSource BindingSource1 = new BindingSource();
        private TextBox textBox1 = new TextBox();
        private TextBox textBox2 = new TextBox();
        private Button button1 = new Button();

        public Form1()
        {
            this.Load += new EventHandler(Form1_Load);
            textBox1.Location = new System.Drawing.Point(118, 131);
            textBox1.ReadOnly = true;
            button1.Location = new System.Drawing.Point(133, 60);
            button1.Click += new EventHandler(button1_Click);
            button1.Text = "Get zipcode";
            ClientSize = new System.Drawing.Size(292, 266);
            Controls.Add(this.button1);
            Controls.Add(this.textBox1);
        }

        private void button1_Click(object sender, EventArgs e)
        {

            textBox1.Text = "Calling Web service..";
            ZipCodeResolver resolver = new ZipCodeResolver();
            BindingSource1.Add(resolver.CorrectedAddressXml("0",
                    "One Microsoft Way", "Redmond", "WA"));
                        
        }

        public void Form1_Load(object sender, EventArgs e)
        {
            BindingSource1.DataSource = typeof(USPSAddress);
            textBox1.DataBindings.Add("Text", this.BindingSource1, "FullZIP", true);
        }
    }

    [System.Web.Services.WebServiceBindingAttribute(Name="ZipCodeResolverSoap",
        Namespace="http://webservices.eraserver.net/")]
    public class ZipCodeResolver:
        System.Web.Services.Protocols.SoapHttpClientProtocol

    {
        
        public ZipCodeResolver() : base()
        {        
            this.Url = 
                "http://webservices.eraserver.net/zipcoderesolver/zipcoderesolver.asmx";
        }

    
        //''<remarks/>
        [System.Web.Services.Protocols.SoapDocumentMethodAttribute
            ("http://webservices.eraserver.net/CorrectedAddressXml", 
            RequestNamespace="http://webservices.eraserver.net/", 
            ResponseNamespace="http://webservices.eraserver.net/", 
            Use=System.Web.Services.Description.SoapBindingUse.Literal, 
            ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
        public USPSAddress CorrectedAddressXml(string accessCode, 
            string address, string city, string state)
        {
            object[] results = this.Invoke("CorrectedAddressXml", 
                new object[]{accessCode, address, city, state});
            return ((USPSAddress) results[0]);
        }

        //''<remarks/>
        public System.IAsyncResult BeginCorrectedAddressXml(string accessCode,
            string address, string city, string state, 
            System.AsyncCallback callback, object asyncState)
        {

            return this.BeginInvoke("CorrectedAddressXml", 
                new object[]{accessCode, address, city, state}, callback, asyncState);
        }


        public USPSAddress EndCorrectedAddressXml(System.IAsyncResult asyncResult)
        {
            object[] results = this.EndInvoke(asyncResult);
            return ((USPSAddress) results[0]);
        }

    }


    [System.SerializableAttribute, System.Xml.Serialization.XmlTypeAttribute(
        Namespace="http://webservices.eraserver.net/")]
    public class USPSAddress
    {

        private string streetField;

        private string cityField;

        private string stateField;

        private string shortZIPField;

        private string fullZIPField;


        public string Street    
        {
            get
            {
                return this.streetField;
            }
            set
            {
                this.streetField = value;
            }
        }


        public string City    
        {
            get
            {
                return this.cityField;
            }
            set
            {
                this.cityField = value;
            }
        }

        public string State    
        {
            get
            {
                return this.stateField;
            }
            set
            {
                this.stateField = value;
            }
        }


        public string ShortZIP    
        {
            get
            {
                return this.shortZIPField;
            }
            set
            {
                this.shortZIPField = value;
            }
        }


        public string FullZIP    
        {
            get
            {
                return this.fullZIPField;
            }
            set
            {
                this.fullZIPField = value;
            }
        }
    }

    public delegate void CorrectedAddressXmlCompletedEventHandler(object sender,
        CorrectedAddressXmlCompletedEventArgs args);


    public class CorrectedAddressXmlCompletedEventArgs:
    System.ComponentModel.AsyncCompletedEventArgs

    {
        private object[] results;

        internal CorrectedAddressXmlCompletedEventArgs(object[] results,
            System.Exception exception, bool cancelled, object userState) :
            base(exception, cancelled, userState)
        {        
            this.results = results;
        }


        public USPSAddress Result    
        {
            get
            {
                this.RaiseExceptionIfNecessary();
                return ((USPSAddress) this.results[0]);
            }
        }
    }
 }
#using <System.Windows.Forms.dll>
#using <System.dll>
#using <System.Drawing.dll>
#using <System.Web.Services.dll>
#using <System.Xml.dll>

using namespace System;
using namespace System::Collections::Generic;
using namespace System::ComponentModel;
using namespace System::Drawing;
using namespace System::Windows::Forms;

namespace BindToWebService {

    [System::SerializableAttribute, System::Xml::Serialization::XmlTypeAttribute(
        Namespace="http://webservices.eraserver.net/")]
    public ref class USPSAddress
    {

private:
        String^ streetField;

        String^ cityField;

        String^ stateField;

        String^ shortZIPField;

        String^ fullZIPField;


public:
        property String^ Street    
        {
            String^ get()
            {
                return this->streetField;
            }
            void set( String^ value )
            {
                this->streetField = value;
            }
        }


        property String^ City    
        {
            String^ get()
            {
                return this->cityField;
            }
            void set( String^ value )
            {
                this->cityField = value;
            }
        }
        property String^ State    
        {
            String^ get()
            {
                return this->stateField;
            }
            void set( String^ value )
            {
                this->stateField = value;
            }
        }

        property String^ ShortZIP    
        {
            String^ get()
            {
                return this->shortZIPField;
            }
            void set( String^ value )
            {
                this->shortZIPField = value;
            }
        }

        property String^ FullZIP    
        {
            String^ get()
            {
                return this->fullZIPField;
            }
            void set( String^ value )
            {
                this->fullZIPField = value;
            }
        }
    };


    [System::Web::Services::WebServiceBindingAttribute(Name="ZipCodeResolverSoap",
        Namespace="http://webservices.eraserver.net/")]
    public ref class ZipCodeResolver:
        public System::Web::Services::Protocols::SoapHttpClientProtocol

    {
        
public:
        ZipCodeResolver() : SoapHttpClientProtocol()
        {        
            this->Url = 
                "http://webservices.eraserver.net/zipcoderesolver/zipcoderesolver.asmx";
        }

    
        //''<remarks/>
        [System::Web::Services::Protocols::SoapDocumentMethodAttribute
            ("http://webservices.eraserver.net/CorrectedAddressXml", 
            RequestNamespace="http://webservices.eraserver.net/", 
            ResponseNamespace="http://webservices.eraserver.net/", 
            Use=System::Web::Services::Description::SoapBindingUse::Literal, 
            ParameterStyle=System::Web::Services::Protocols::SoapParameterStyle::Wrapped)]
        USPSAddress^ CorrectedAddressXml(String^ accessCode, 
            String^ address, String^ city, String^ state)
        {
            array<Object^>^ results = this->Invoke("CorrectedAddressXml", 
                gcnew array<Object^>{accessCode, address, city, state});
            return ((USPSAddress^) results[0]);
        }

        //''<remarks/>
        System::IAsyncResult^ BeginCorrectedAddressXml(String^ accessCode,
            String^ address, String^ city, String^ state, 
            System::AsyncCallback^ callback, Object^ asyncState)
        {

            return this->BeginInvoke("CorrectedAddressXml", 
                gcnew array<Object^>{accessCode, address, city, state}, callback, asyncState);
        }


        USPSAddress^ EndCorrectedAddressXml(System::IAsyncResult^ asyncResult)
        {
            array<Object^>^ results = this->EndInvoke(asyncResult);
            return ((USPSAddress^) results[0]);
        }

    };

    ref class Form1: public Form
    {
public:
        [STAThread]
        static void Main()
        {
            Application::EnableVisualStyles();
            Application::Run(gcnew Form1());
        }

private:
        BindingSource^ BindingSource1;

        TextBox^ textBox1;

        TextBox^ textBox2;

        Button^ button1;


public:
        Form1()
        {
            this->Load += gcnew EventHandler(this, &Form1::Form1_Load);
            textBox1->Location = System::Drawing::Point(118, 131);
            textBox1->ReadOnly = true;
            button1->Location = System::Drawing::Point(133, 60);
            button1->Click += gcnew EventHandler(this, &Form1::button1_Click);
            button1->Text = "Get zipcode";
            ClientSize = System::Drawing::Size(292, 266);
            Controls->Add(this->button1);
            Controls->Add(this->textBox1);
                        BindingSource1 = gcnew BindingSource();
                        textBox1 = gcnew TextBox();
                        textBox2 = gcnew TextBox();
                        button1 = gcnew Button();
        }

private:
        void button1_Click(Object^ sender, EventArgs^ e)
        {
            textBox1->Text = "Calling Web service..";
            ZipCodeResolver^ resolver = gcnew ZipCodeResolver();
            BindingSource1->Add(resolver->CorrectedAddressXml("0",
                    "One Microsoft Way", "Redmond", "WA"));
                        
        }

public:
        void Form1_Load(Object^ sender, EventArgs^ e)
        {
            BindingSource1->DataSource = USPSAddress::typeid;
            textBox1->DataBindings->Add("Text", this->BindingSource1, "FullZIP", true);
        }
    };




    public ref class CorrectedAddressXmlCompletedEventArgs:
    public System::ComponentModel::AsyncCompletedEventArgs

    {
private:
        array<Object^>^ results;

internal:
        CorrectedAddressXmlCompletedEventArgs(array<Object^>^ results,
            System::Exception^ exception, bool cancelled, Object^ userState) :
            AsyncCompletedEventArgs(exception, cancelled, userState)
        {        
            this->results = results;
        }


public:
        property USPSAddress^ Result    
        {
            USPSAddress^ get()
            {
                this->RaiseExceptionIfNecessary();
                return ((USPSAddress^) this->results[0]);
            }
        }

     delegate void CorrectedAddressXmlCompletedEventHandler(Object^ sender,
        CorrectedAddressXmlCompletedEventArgs^ args);

    };
}

int main()
{
    BindToWebService::Form1::Main();
    return 1;
}

編譯程式碼

這是包含 Main 方法的完整範例,同時也是用戶端 Proxy 程式碼的縮短版本。

這個範例需要:

  • System、System.Drawing、System.Web.Services、System.Windows.Forms 和 System.Xml 組件的參考。

如需從 Visual Basic 或 Visual C# 的命令列建置這個範例的詳細資訊,請參閱從命令列建置 (Visual Basic)使用 csc.exe 建置命令列。您也可以透過將程式碼貼入新的專案,在 Visual Studio 中建置此範例。

請參閱

工作

HOW TO:將 Windows Form 控制項繫結至型別

其他資源

BindingSource 元件