IWebPartTable 接口

定义

使用整个数据表定义一个用于连接两个服务器控件的提供者接口。

public interface class IWebPartTable
public interface IWebPartTable
type IWebPartTable = interface
Public Interface IWebPartTable

示例

下面的代码示例演示如何使用 IWebPartTable 接口在两个控件之间创建静态连接。 代码示例有三个部分:

  • 两个自定义控件的源代码,这些控件 WebPart 可以使用接口形成连接 IWebPartTable ,一个控件充当提供程序,另一个控件充当使用者。

  • 承载控件并声明持久性格式的静态连接的网页。

  • 有关示例代码运行时发生的情况的说明。

代码示例的第一部分是两个自定义控件的源代码。 首先是实现接口的提供程序 IWebPartTable 的代码。 为简单起见,提供程序会创建包含某些数据的表,而不是连接到数据库。 该方法 GetConnectionInterface 充当提供程序的连接点,即将接口实例返回到使用者的回调方法。 至于使用者,它将从名为 SetConnectionInterface 的提供程序中检索接口实例,该接口实例用 ConnectionConsumer 属性标记。 检索接口实例后,使用者在其方法中 OnPreRender 调用提供程序中方法的 GetTableData 实现,以检索实际数据并将其写入页面。

若要运行代码示例,必须编译此源代码。 可以显式编译它,并将生成的程序集放入网站的 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 table data.
  [AspNetHostingPermission(SecurityAction.Demand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  [AspNetHostingPermission(SecurityAction.InheritanceDemand,
    Level = AspNetHostingPermissionLevel.Minimal)]
    public sealed class TableProviderWebPart : WebPart, IWebPartTable
    {
        DataTable _table;

        public TableProviderWebPart()
        {
            _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);
        }

        public PropertyDescriptorCollection Schema
        {
            get
            {
                return TypeDescriptor.GetProperties(_table.DefaultView[0]);
            }
        }

        public void GetTableData(TableCallback callback)
        {
                callback(_table.Rows);
        }

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

        [ConnectionProvider("Table", typeof(TableProviderConnectionPoint), 
      AllowsMultipleConnections = true)]
        public IWebPartTable GetConnectionInterface()
        {
            return new TableProviderWebPart();
        }

        public class TableProviderConnectionPoint : ProviderConnectionPoint
        {
            public TableProviderConnectionPoint(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 ((TableProviderWebPart)control).ConnectionPointEnabled;
            }
        }
    }

  // This code sample creates a Web Parts control that acts as a consumer 
  // of information provided by the TableProvider.ascx control.
  [AspNetHostingPermission(SecurityAction.Demand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  [AspNetHostingPermission(SecurityAction.InheritanceDemand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  public class TableConsumer : WebPart
  {
    private IWebPartTable _provider;
    private ICollection _tableData;

    private void GetTableData(object tableData)
    {
      _tableData = (ICollection)tableData;
    }

    protected override void OnPreRender(EventArgs e)
    {
      if (_provider != null)
      {
        _provider.GetTableData(new TableCallback(GetTableData));
      }
    }

    protected override void RenderContents(HtmlTextWriter writer)
    {
      if (_provider != null)
      {
        PropertyDescriptorCollection props = _provider.Schema;
        int count = 0;
        if (props != null && props.Count > 0 && _tableData != null)
        {
          foreach (PropertyDescriptor prop in props)
          {
            foreach (DataRow o in _tableData)
            {
              writer.Write(prop.DisplayName + ": " + o[count]);
            }
            writer.WriteBreak();
            writer.WriteLine();
            count = count + 1;
          }
        }
        else
        {
          writer.Write("No data");
        }
      }
      else
      {
        writer.Write("Not connected");
      }
    }

    [ConnectionConsumer("Table")]
    public void SetConnectionInterface(IWebPartTable provider)
    {
      _provider = provider;
    }

    public class TableConsumerConnectionPoint : ConsumerConnectionPoint
    {
      public TableConsumerConnectionPoint(MethodInfo callbackMethod,
        Type interfaceType, Type controlType, string name, string id,
        bool allowsMultipleConnections)
        : base(callbackMethod, interfaceType, controlType, name, id,
        allowsMultipleConnections)
      {
      }
    } // TableConsumerConnectionPoint
  } // TableConsumer
} // 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 table data.
  <AspNetHostingPermission(SecurityAction.Demand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  <AspNetHostingPermission(SecurityAction.InheritanceDemand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  Public NotInheritable Class TableProviderWebPart
    Inherits WebPart
    Implements IWebPartTable
    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


    Public ReadOnly Property Schema() As _
      ComponentModel.PropertyDescriptorCollection Implements IWebPartTable.Schema

      Get
        Return TypeDescriptor.GetProperties(_table.DefaultView(0))
      End Get

    End Property


    Public Sub GetTableData(ByVal callback As TableCallback) _
      Implements IWebPartTable.GetTableData

      callback(_table.Rows)

    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


    <ConnectionProvider("Table", GetType(TableProviderConnectionPoint), _
      AllowsMultipleConnections:=True)> _
    Public Function GetConnectionInterface() As IWebPartTable

      Return New TableProviderWebPart()

    End Function

  End Class

  ' The connection point for the provider control.
  <AspNetHostingPermission(SecurityAction.Demand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  <AspNetHostingPermission(SecurityAction.InheritanceDemand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  Public Class TableProviderConnectionPoint
    Inherits ProviderConnectionPoint

    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, TableProviderWebPart).ConnectionPointEnabled

    End Function
  End Class


  ' This code sample creates a Web Parts control that acts as a consumer 
  ' of information provided by the TableProvider.ascx control.
  <AspNetHostingPermission(SecurityAction.Demand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  <AspNetHostingPermission(SecurityAction.InheritanceDemand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  Public Class TableConsumer
    Inherits WebPart
    Private _provider As IWebPartTable
    Private _tableData As ICollection


    Private Sub GetTableData(ByVal tableData As ICollection)
      _tableData = CType(tableData, ICollection)

    End Sub


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

    End Sub


    Protected Overrides Sub RenderContents(ByVal writer As HtmlTextWriter)
      If Not (_provider Is Nothing) Then
        Dim props As PropertyDescriptorCollection = _provider.Schema
        Dim count As Integer = 0
        If Not (props Is Nothing) AndAlso props.Count > 0 _
          AndAlso Not (_tableData Is Nothing) Then

          Dim prop As PropertyDescriptor
          For Each prop In props
            Dim o As DataRow
            For Each o In _tableData
              writer.Write(prop.DisplayName & ": " & o(count))
            Next o
            writer.WriteBreak()
            writer.WriteLine()
            count = count + 1
          Next prop
        Else
          writer.Write("No data")
        End If
      Else
        writer.Write("Not connected")
      End If

    End Sub


    <ConnectionConsumer("Table")> _
    Public Sub SetConnectionInterface(ByVal provider As IWebPartTable)
      _provider = provider

    End Sub

  End Class

  ' The connection point for the consumer control.
  <AspNetHostingPermission(SecurityAction.Demand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  <AspNetHostingPermission(SecurityAction.InheritanceDemand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  Public Class TableConsumerConnectionPoint
    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
  End Class

End Namespace  ' Samples.AspNet.CS.Controls

代码示例的第二部分是声明静态连接并承载控件的网页。 页面顶部附近是一个 Register 指令,用于声明包含在 App_Code 目录中的源代码的命名空间。 连接是使用 <asp:webpartconnection> 元素声明的。 自定义使用者和提供程序控件在元素内的元素中<zonetemplate>``<asp:webpartzone>声明,这需要这些控件才能连接 (它们必须驻留在继承自WebPartZoneBase类) 的区域内。

<%@ page language="C#" %>
<%@ Register tagprefix="IRow" 
    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">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>IRow Test Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:webpartmanager ID="WebPartManager1" runat="server">
        <staticconnections>
          <asp:webpartconnection ID="wp1" ProviderID="provider1" 
            ConsumerID="consumer1">
          </asp:webpartconnection>
        </staticconnections>
      </asp:webpartmanager>
       
        <asp:webpartzone ID="WebPartZone1" runat="server">
          <ZoneTemplate>
            <irow:RowProviderWebPart ID="provider1" runat="server" 
              Title="Row Provider Control" />
            <irow:RowConsumerWebPart ID="consumer1" runat="server" 
              Title="Row Consumer Control" />
          </ZoneTemplate>
        </asp:webpartzone>
    </div>
    </form>
</body>
</html>
<%@ page language="VB" %>
<%@ Register tagprefix="IRow" 
    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">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>IRow Test Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:webpartmanager ID="WebPartManager1" runat="server">
        <staticconnections>
          <asp:webpartconnection ID="wp1" ProviderID="provider1" 
            ConsumerID="consumer1">
          </asp:webpartconnection>
        </staticconnections>
      </asp:webpartmanager>
       
        <asp:webpartzone ID="WebPartZone1" runat="server">
          <ZoneTemplate>
            <irow:RowProviderWebPart ID="provider1" runat="server" 
              Title="Row Provider Control" />
            <irow:RowConsumerWebPart ID="consumer1" runat="server" 
              Title="Row Consumer Control" />
          </ZoneTemplate>
        </asp:webpartzone>
    </div>
    </form>
</body>
</html>

在浏览器中加载页面。 使用者控件显示从指定表提供的数据,提供程序通过接口的 IWebPartTable 实例提供这些数据。

注解

此接口旨在与Web 部件连接一起使用。 在Web 部件连接中,驻留在WebPartZoneBase区域中的两个服务器控件建立连接并共享数据,一个控件充当使用者,另一个控件充当提供程序。 在Web 部件连接中共享数据的机制是接口实例,提供程序通过回调方法向使用者提供服务。 若要建立连接,使用者和提供程序必须使用相同的接口类型来共享数据。 如果使用者无法识别提供程序发送的接口类型,则仍可以通过转换器 (对象) WebPartTransformer 将提供程序发送的接口实例转换为使用者识别的类型来连接控件。 有关连接的详细信息,请参阅WebPartConnectionWeb 部件连接概述

IWebPartTable接口是一个提供程序接口,其中包含Web 部件控件集作为标准接口,用于基于数据表创建连接。 还可以创建自定义接口以用于Web 部件连接,但在许多数据驱动的 Web 应用程序中,基于常见字段 (创建连接非常有用,有关详细信息,请参阅接口) 、行 (了解详细信息、查看IWebPartFieldIWebPartRow接口) 或数据源中的表。 在典型的连接中, WebPart 充当提供程序的 IWebPartTable 控件将实现接口,并在特殊回调方法中向使用者提供接口实例。 例如,提供程序可能为包含财务性能数据的表实现 IWebPartTable 接口。 另一 WebPart 个充当使用者的控件将定义用于接收接口实例的特殊方法,然后可以提取数据并呈现图表以显示结果信息。

IWebPartTable 接口有两个公开的成员。 该 Schema 属性返回有关封装在对象中的 PropertyDescriptorCollection 数据表的架构信息。 该方法 GetTableData 声明实现者 (的方法,如提供程序控件,) 调用回调方法时检索接口实例的表数据。

属性

Schema

获取用于在两个 WebPart 控件之间共享数据的数据表的架构信息。

方法

GetTableData(TableCallback)

返回表的数据,该表正由接口用作两个 WebPart 控件之间的连接基础。

适用于

另请参阅