IWebPartField 介面

定義

使用單一資料欄位,定義連接兩個伺服器控制項的提供者介面。

public interface class IWebPartField
public interface IWebPartField
type IWebPartField = interface
Public Interface IWebPartField
衍生

範例

下列程式碼範例示範如何使用 介面,在兩個控制項 IWebPartField 之間建立靜態連接。 程式碼範例有三個部分:

  • 兩個自訂 WebPart 控制項的原始程式碼,這些控制項可以使用 介面形成連接 IWebPartField ,其中一個控制項做為提供者,另一個控制項則做為取用者。

  • 裝載控制項並以持續性格式宣告靜態連線的網頁。

  • 範例程式碼執行時會發生什麼情況的描述。

程式碼範例的第一個部分是兩個自訂控制項的原始程式碼。 首先,是實作 IWebPartField 介面的提供者程式碼。 為了簡單起見,提供者會建立含有某些資料的資料表,而不是連接到資料庫。 方法 GetConnectionInterface 可作為提供者的連接點,這個回呼方法會將介面實例傳回給取用者。 就取用者而言,它會從名為 的 提供者 SetConnectionInterface 中擷取介面實例,並以 屬性標示 ConnectionConsumer 。 擷取介面的實例之後,取用者在其 OnPreRender 方法中呼叫 提供者中 方法的 GetFieldValue 實作,以擷取實際資料。

若要執行程式碼範例,您必須編譯此原始程式碼。 您可以明確地編譯它,並將產生的元件放在網站的 Bin 資料夾或全域組件快取中。 或者,您可以將原始程式碼放在月臺的App_Code資料夾中,在執行時間將動態編譯。 此程式碼範例使用動態編譯。 如需示範如何編譯的逐步解說,請參閱逐步解說 :開發和使用自訂 Web 服務器控制項

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Reflection;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace Samples.AspNet.CS.Controls
{
  // This sample code creates a Web Parts control that acts as a provider 
  // of field data.
  [AspNetHostingPermission(SecurityAction.Demand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  [AspNetHostingPermission(SecurityAction.InheritanceDemand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  public sealed class FieldProviderWebPart : WebPart, IWebPartField
  {
    private DataTable _table;

    public FieldProviderWebPart() 
    {
        _table = new DataTable();

        DataColumn col = new DataColumn();
        col.DataType = typeof(string);
        col.ColumnName = "Name";
        _table.Columns.Add(col);

        col = new DataColumn();
        col.DataType = typeof(string);
        col.ColumnName = "Address";
        _table.Columns.Add(col);

        col = new DataColumn();
        col.DataType = typeof(int);
        col.ColumnName = "ZIP Code";
        _table.Columns.Add(col);

        DataRow row = _table.NewRow();
        row["Name"] = "John Q. Public";
        row["Address"] = "123 Main Street";
        row["ZIP Code"] = 98000;
        _table.Rows.Add(row);
    }

      [ConnectionProvider("FieldProvider")]
      public IWebPartField GetConnectionInterface()
    {
        return new FieldProviderWebPart();
    }

    public PropertyDescriptor Schema 
    {
        get 
        {
            /* The two parameters are row and field. Zero is the first record. 
                0,2 returns the zip code field value.   */ 
            return TypeDescriptor.GetProperties(_table.DefaultView[0])[2];
        }
    }

      void IWebPartField.GetFieldValue(FieldCallback callback) 
    {
        callback(Schema.GetValue(_table.DefaultView[0]));
    }
  } // end FieldProviderWebPart

  // This sample code creates a Web Parts control that acts as a consumer 
  // of an IWebPartField interface.
  [AspNetHostingPermission(SecurityAction.Demand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  [AspNetHostingPermission(SecurityAction.InheritanceDemand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  public class FieldConsumerWebPart : WebPart
  {

    private IWebPartField _provider;
    private object _fieldValue;

    private void GetFieldValue(object fieldValue)
    {
      _fieldValue = fieldValue;
    }

    public bool ConnectionPointEnabled
    {
      get
      {
        object o = ViewState["ConnectionPointEnabled"];
        return (o != null) ? (bool)o : true;
      }
      set
      {
        ViewState["ConnectionPointEnabled"] = value;
      }
    }

    protected override void OnPreRender(EventArgs e)
    {
      if (_provider != null)
      {
        _provider.GetFieldValue(new FieldCallback(GetFieldValue));
      }
      base.OnPreRender(e);
    }

    protected override void RenderContents(HtmlTextWriter writer)
    {

      if (_provider != null)
      {
        PropertyDescriptor prop = _provider.Schema;

        if (prop != null && _fieldValue != null)
        {
          writer.Write(prop.DisplayName + ": " + _fieldValue);
        }
        else
        {
          writer.Write("No data");
        }
      }
      else
      {
        writer.Write("Not connected");
      }
    }

    [ConnectionConsumer("FieldConsumer", "Connpoint1", 
      typeof(FieldConsumerConnectionPoint), AllowsMultipleConnections = true)]
    public void SetConnectionInterface(IWebPartField provider)
    {
      _provider = provider;
    }

    public class FieldConsumerConnectionPoint : ConsumerConnectionPoint
    {
      public FieldConsumerConnectionPoint(MethodInfo callbackMethod, 
        Type interfaceType, Type controlType, string name, string id, 
        bool allowsMultipleConnections)
        : base(
        callbackMethod, interfaceType, controlType,
        name, id, allowsMultipleConnections)
      {
      }

      public override bool GetEnabled(Control control)
      {
        return ((FieldConsumerWebPart)control).ConnectionPointEnabled;
      }
    } // end FieldConsumerConnectionPoint
  } // end FieldConsumerWebPart
} // end namespace Samples.AspNet.CS.Controls
Imports System.Collections
Imports System.ComponentModel
Imports System.Data
Imports System.Reflection
Imports System.Security.Permissions
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts

Namespace Samples.AspNet.VB.Controls

  ' This sample code creates a Web Parts control that acts as a 
  ' provider of field data.
  <AspNetHostingPermission(SecurityAction.Demand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  <AspNetHostingPermission(SecurityAction.InheritanceDemand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  Public NotInheritable Class FieldProviderWebPart
    Inherits WebPart
    Implements IWebPartField
    Private _table As DataTable


    Public Sub New()
      _table = New DataTable()

      Dim col As New DataColumn()
      col.DataType = GetType(String)
      col.ColumnName = "Name"
      _table.Columns.Add(col)

      col = New DataColumn()
      col.DataType = GetType(String)
      col.ColumnName = "Address"
      _table.Columns.Add(col)

      col = New DataColumn()
      col.DataType = GetType(Integer)
      col.ColumnName = "ZIP Code"
      _table.Columns.Add(col)

      Dim row As DataRow = _table.NewRow()
      row("Name") = "John Q. Public"
      row("Address") = "123 Main Street"
      row("ZIP Code") = 98000
      _table.Rows.Add(row)

    End Sub


    <ConnectionProvider("FieldProvider")> _
    Public Function GetConnectionInterface() As IWebPartField
      Return New FieldProviderWebPart()

    End Function


    Public ReadOnly Property Schema() As ComponentModel.PropertyDescriptor _
      Implements IWebPartField.Schema
      Get
        ' The two parameters are row and field. Zero is the first record. 
        ' 0,2 returns the zip code field value.   
        Return TypeDescriptor.GetProperties(_table.DefaultView(0))(2)
      End Get
    End Property


    Sub GetFieldValue(ByVal callback As FieldCallback) _
      Implements IWebPartField.GetFieldValue

      callback(Schema.GetValue(_table.DefaultView(0)))

    End Sub

  End Class


  ' This sample code creates a Web Parts control that acts as a 
  ' consumer of an IWebPartField interface.
  <AspNetHostingPermission(SecurityAction.Demand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  <AspNetHostingPermission(SecurityAction.InheritanceDemand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  Public Class FieldConsumerWebPart
    Inherits WebPart

    Private _provider As IWebPartField
    Private _fieldValue As Object


    Private Sub GetFieldValue(ByVal fieldValue As Object)
      _fieldValue = fieldValue

    End Sub


    Public Property ConnectionPointEnabled() As Boolean
      Get
        Dim o As Object = ViewState("ConnectionPointEnabled")
        Return IIf(Not (o Is Nothing), CBool(o), True)
      End Get
      Set(ByVal value As Boolean)
        ViewState("ConnectionPointEnabled") = value
      End Set
    End Property


    Protected Overrides Sub OnPreRender(ByVal e As EventArgs)
      If Not (_provider Is Nothing) Then
        _provider.GetFieldValue(New FieldCallback(AddressOf GetFieldValue))
      End If
      MyBase.OnPreRender(e)

    End Sub


    Protected Overrides Sub RenderContents(ByVal writer As _
      HtmlTextWriter)

      If Not (_provider Is Nothing) Then
        Dim prop As PropertyDescriptor = _provider.Schema

        If Not (prop Is Nothing) AndAlso Not (_fieldValue Is Nothing) Then
          writer.Write(prop.DisplayName & ": " & _fieldValue)
        Else
          writer.Write("No data")
        End If
      Else
        writer.Write("Not connected")
      End If

    End Sub

    <ConnectionConsumer("FieldConsumer", "Connpoint1", _
      GetType(FieldConsumerConnectionPoint), AllowsMultipleConnections:=True)> _
    Public Sub SetConnectionInterface(ByVal provider As IWebPartField)
      _provider = provider

    End Sub

  End Class

  Public Class FieldConsumerConnectionPoint
    Inherits ConsumerConnectionPoint

    Public Sub New(ByVal callbackMethod As MethodInfo, _
      ByVal interfaceType As Type, ByVal controlType As Type, _
      ByVal name As String, ByVal id As String, _
      ByVal allowsMultipleConnections As Boolean)
      MyBase.New(callbackMethod, interfaceType, controlType, _
        name, id, allowsMultipleConnections)

    End Sub


    Public Overrides Function GetEnabled(ByVal control As Control) _
      As Boolean

      Return CType(control, FieldConsumerWebPart).ConnectionPointEnabled

    End Function

  End Class

End Namespace  ' Samples.AspNet.VB.Controls

程式碼範例的第二個部分是宣告靜態連線並裝載控制項的網頁。 靠近頁面頂端的 Register 指示詞,會宣告包含在 App_Code 目錄中之原始程式碼的命名空間。 連接是使用 <asp:webpartconnection> 元素宣告的。 自訂取用者和提供者控制項是在元素內的元素中 <zonetemplate> <asp:webpartzone> 宣告,因此必須能夠連接 (它們必須位於繼承自 WebPartZoneBase 類別) 的區域。

<%@ page language="C#" %>
<%@ Register tagprefix="IField" 
    Namespace="Samples.AspNet.CS.Controls" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<!-- This code sample creates a page with two Web Parts controls 
and establishes a connection between the controls. -->
<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>IWebPartField Test Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:webpartmanager id="WebPartManager1" runat="server">
            <StaticConnections>
                <asp:WebPartConnection id="con1" ProviderID="provider1" 
                  ConsumerID="consumer1" 
                  ConsumerConnectionPointID="Connpoint1">
                </asp:WebPartConnection>
            </StaticConnections>
        </asp:webpartmanager>
        <asp:webpartzone id="WebPartZone1" runat="server">
            <zoneTemplate>
              <ifield:fieldproviderwebpart runat="Server" 
                ID="provider1" Title="Provider" />
              <ifield:fieldconsumerwebpart runat="Server" 
                ID="consumer1" Title="Consumer"/>
            </zoneTemplate>
        </asp:webpartzone>
    
    </div>
    </form>
</body>
</html>
<%@ page language="VB" debug="true" %>
<%@ Register tagprefix="IField" 
    Namespace="Samples.AspNet.VB.Controls" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<!-- This code sample creates a page with two Web Parts controls 
and establishes a connection between the controls. -->
<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>IWebPartField Test Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:webpartmanager id="WebPartManager1" runat="server">
            <StaticConnections>
                <asp:WebPartConnection id="con1" ProviderID="provider1" 
                  ConsumerID="consumer1" 
                  ConsumerConnectionPointID="Connpoint1">
                </asp:WebPartConnection>
            </StaticConnections>
        </asp:webpartmanager>
        <asp:webpartzone id="WebPartZone1" runat="server">
            <zoneTemplate>
              <ifield:fieldproviderwebpart runat="Server" 
                ID="provider1" Title="Provider" />
              <ifield:fieldconsumerwebpart runat="Server" 
                ID="consumer1" Title="Consumer"/>
            </zoneTemplate>
        </asp:webpartzone>
    </div>
    </form>
</body>
</html>

在瀏覽器中載入頁面。 取用者控制項會顯示指定欄位所提供的資料,提供者會透過 介面的 IWebPartField 實例提供。

備註

此介面的設計目的是要與Web 組件連線搭配使用。 在Web 組件連線中,位於 WebPartZoneBase 區域中的兩個伺服器控制項會建立連線並共用資料,其中一個控制項做為取用者,另一個控制項做為提供者。 在Web 組件連線中共用資料的機制是介面實例,提供者會透過回呼方法提供給取用者。 若要建立連線,取用者和提供者必須同時使用相同的介面類別型來共用資料。 如果取用者無法辨識提供者所傳送的介面類別型,您仍然可以透過轉換程式來連接控制項, (WebPartTransformer 物件) 將提供者所傳送的介面實例轉譯為取用者辨識的類型。 如需連線的詳細資訊,請參閱 WebPartConnectionWeb 組件連線概觀

介面 IWebPartField 是提供者介面,隨附于Web 組件控制項集,作為根據資料欄位建立連線的標準介面。 您也可以建立自訂介面來與Web 組件連線搭配使用,但在許多資料驅動 Web 應用程式中,使用 介面建立連線會很有用 (一般資料列,如需詳細資訊,請參閱介面) 、資料表 (以取得詳細資料、請參閱 IWebPartRow IWebPartTable 介面) 或資料來源 IWebPartField 中的欄位。 在一般連線中, WebPart 做為提供者的控制項會實 IWebPartField 作 介面,並在特殊回呼方法中將介面的實例提供給取用者。 例如,提供者可能會針對 IWebPartField 使用者資訊表中包含 Web 使用者的郵遞區號資料欄位實作介面。 另一個 WebPart 做為取用者的控制項會定義特殊方法來接收介面實例,然後擷取郵遞區號資料,並根據郵遞區號查閱及顯示天氣資訊。

介面 IWebPartField 有兩個公開的成員。 屬性 Schema 會傳回 物件中 PropertyDescriptor 封裝之資料欄位的架構資訊。 方法 GetFieldValue 會宣告實作者 (的方法,例如提供者控制項,) 叫用回呼方法時,用來擷取介面實例的欄位資料。

屬性

Schema

取得資料欄位的結構描述資訊,這個資料欄位是用於兩個 WebPart 控制項之間共用資料。

方法

GetFieldValue(FieldCallback)

傳回資料欄位的值,介面正在將此資料欄位用作兩個 WebPart 控制項之間連接的基礎。

適用於

另請參閱