共用方式為


IFilterConsumer Interface

NOTE: This API is now obsolete.

Used to consume a filter expression from a Web Part that has implemented an IFilterProvider interface.

Namespace:  Microsoft.SharePoint.WebPartPages.Communication
Assembly:  Microsoft.SharePoint (in Microsoft.SharePoint.dll)

Syntax

'Declaration
<ObsoleteAttribute("Use System.Web.UI.WebControls.WebParts.IWebPartParameters instead")> _
Public Interface IFilterConsumer
'Usage
Dim instance As IFilterConsumer
[ObsoleteAttribute("Use System.Web.UI.WebControls.WebParts.IWebPartParameters instead")]
public interface IFilterConsumer

Remarks

The IFilterConsumer interface should be used with parts that need to consume a collection of one or more filter values. The event handlers of IFilterConsumer were designed for the purpose of setting and clearing multiple filter values. The IFilterConsumer part has the ability to send initialization arguments to the provider part. The IFilterConsumer can be connected to the IFilterProvider and IRowProvider interfaces. When connecting the IFilterConsumer to IFilterProvider, this is a direct connection so no transformer dialog will be displayed. To appropriately use the passed values, the consuming part may need to be designed with an understanding of the data passed by the provider. When connecting the IFilterConsumer to IRowProvider, a transformer dialog will be displayed which allows an end user to map the column in the row to the filter input. Only one value can be mapped, but it gives the end user the ability to change the filter mapping at any time. Server side implementations of IFilterConsumer can also be connected to parts on a different page by using an HTML editor compatible with Microsoft SharePoint Foundation, such as Microsoft SharePoint Designer.

Examples

The following code example shows a server-side IFilterConsumer Web Part. It can be connected to another Web Part which implements the IFilterProvider or IRowProvider interface on the server. The IFilterConsumer Web Part displays a list which can be filtered by the values sent by a provider Web Part.

There are 11 steps specific to making this a connectable Web Part. These steps are numbered and commented in the following code example.

For more information on creating a connectable Web Part, see Creating a Connectable Web Part.

' Common .NET required namespaces
Imports System
Imports System.ComponentModel
Imports System.Web.UI

' Web Part required namespaces
Imports Microsoft.SharePoint.WebPartPages
Imports System.Xml.Serialization
Imports System.Web.UI.WebControls

' Code Access Security namespaces
Imports System.Security
Imports Microsoft.SharePoint.Utilities

' DataGrid and user interface namespaces
Imports System.Data
Imports System.Drawing

' Step #1: Reference the Communication namespace.
Imports Microsoft.SharePoint.WebPartPages.Communication
Namespace ConnectionCodeSamples

   ' Step #2: Implement the IFilterConsumer interface.
   
   Public Class ServerSideFilterConsumer
      Inherits WebPart
      Implements IFilterConsumer
      
      ' Step #3: Declare the IFilterConsumer event.
      ' Because this class implements the IFilterConsumer interface, it 
      ' must declare the interface member FilterConsumerInit. 
      Public Event FilterConsumerInit As FilterConsumerInitEventHandler Implements IFilterConsumer.FilterConsumerInit
      
      ' Declare variables for keeping track of connection state.
      Private _connected As Boolean = False
      Private _connectedWebPartTitle As String = String.Empty
      Private _registrationErrorMsg As String = "An error has occurred trying to register your connection interfaces."
      Private _registrationErrorOccurred As Boolean = False
      Private _notConnectedMsg As String = "NOT CONNECTED. To filter this Web Part connect it to a Filter or Row Provider Web Part."
      
      ' Declare variables for Web Part user interface.
      Private _connectedWebPartLabel As String = "Connected to Web Part"
      Private _convertedRowFilterLabel As String = "Converted Row Filter"
      Private _dataGrid As DataGrid
      Private _rowFilterExpression As String = String.Empty
      Private _cachedRowFilter As TextBox
      
      ' Declare variables for filter field information.
      Private _filterFieldNames() As String
      Private _filterFieldDisplayNames() As String
      Private FieldLabel As String = "FilterField"
      Private ValueLabel As String = "FilterValue"
      
      ' Step #4: Override EnsureInterfaces method and call 
      ' RegisterInterface method.
      ' EnsureInterfaces() is called by the Web Part infrastructure 
      ' during the ASP.NET PreRender event 
      ' and allows the part to register all of its connection 
      ' interfaces.
      Public Overrides Sub EnsureInterfaces()
         ' If your Web Part is installed in the bin directory and the 
         ' Code Access Security (CAS) setting doesn't 
         ' allow Web Part Connections, an exception will be thrown. To 
         ' allow your Web Part to behave well and continue working, a 
         ' try/catch block should be used when attempting to register 
         ' interfaces. Web Part Connections will only work if the level 
         ' attribute of the <trust> tag in the web.config file is set 
         ' to WSS_Minimal, WSS_Medium, or Full. By default a new 
         ' SharePoint site is installed with the trust level set to 
         ' WSS_Minimal.
         Try
            ' Register the IFilterConsumer interface
            ' <param name="interfaceName">Friendly name of the 
            ' interface that is being implemented.</param>
            ' <param name="interfaceType">Specifies which interface is 
            ' being implemented.</param>
            ' <param name="maxConnections">Defines how many times this 
            ' interface can be connected.</param>
            ' <param name="runAtOptions">Determines where the interface 
            ' can run.</param>
            ' <param name="interfaceObject">Reference to the object 
            ' that is implementing this interface.</param>
            ' <param name="interfaceClientReference">Name used to 
            ' reference the interface on the client. 
            ' This is a server side example so the value is set to 
            ' empty string.</param>
            ' <param name="menuLabel">Label for the interface that 
            ' appears in the UI</param>
            ' <param name="description">Description of the interface 
            ' that appears in the UI</param>
            ' <param name="allowCrossPageConnection">Specifies if the 
            ' interface can connect to a Web Part
            ' on a different page. This is an optional parameter with a 
            ' default of false. Note that only some 
            ' server side interfaces are allowed to connect across 
            ' pages by the Web Part infrastructure. 
            ' The IFilterConsumer interface is allowed to connect 
            ' across pages.</param>
            RegisterInterface("MyFilterConsumerInterface", InterfaceTypes.IFilterConsumer, WebPart.LimitOneConnection, ConnectionRunAt.Server, Me, "", "Consume Filter From", "Consumes a Filter from another Web Part.", True)    

         Catch se As SecurityException
            _registrationErrorOccurred = True
         End Try
      End Sub
      
      ' Step #5: Override the CanRunAt method.
      ' CanRunAt() is called by the Web Part infrastructure during the 
      ' ASP.NET PreRender event to determine where the Web Part can run 
      ' based on its current configuration.
      Public Overrides Function CanRunAt() As ConnectionRunAt
         ' This Web Part can run on the server.
         Return ConnectionRunAt.Server
      End Function
      
      ' Step #6: Override the PartCommunicationConnect method.
      ' PartCommunicationConnect() is called by the Web Part 
      ' infrastructure to notify the Web Part that it
      ' is connected during the ASP.NET PreRender event. Relevant 
      ' information is passed to the part such as 
      ' the interface it is connected over, the Web Part it is being 
      ' connected to, and where the part will be running, 
      ' either client or server side. 
      ' <param name="interfaceName">Friendly name of the interface that 
      ' is being connected</param>
      ' <param name="connectedPart">Reference to the other Web Part 
      ' that is being connected to</param>
      ' <param name="connectedInterfaceName">Friendly name of the 
      ' interface on the other Web Part</param>
      ' <param name="runAt">Where the interface should execute</param>
      Public Overrides Sub PartCommunicationConnect(interfaceName As String, connectedPart As WebPart, connectedInterfaceName As String, runAt As ConnectionRunAt)
         'Check if this is my particular Filter interface
         If interfaceName = "MyFilterConsumerInterface" Then
            'Keep track of the Connection
            _connected = True
            _connectedWebPartTitle = SPEncode.HtmlEncode(connectedPart.Title)
         End If
      End Sub
      
      ' Step #7: Override the PartCommunicationInit method.
      ' PartCommunicationInit() is called by the Web Part 
      ' infrastructure during the ASP.NET PreRender event
      ' to allow the part to pass initialization information to the 
      ' other connected parts.
      ' It is important to always pass initialization information. Some 
      ' parts may not behave properly if this initialization 
      ' information is not received.
        Public Overrides Sub PartCommunicationInit()
            ' If the connection wasn't actually formed then don't want 
            ' to send Init event
            If _connected Then
                ' Ensure that all of the Web Part's controls are 
                ' created
                ' The _filterFieldNames and _filterFieldDisplayNames 
                ' are set during EnsureChildControls()
                EnsureChildControls()

                ' Create the FilterConsumerInitEventArgs object for the 
                ' FilterConsumerInit event.
                Dim filterConsumerInitArgs As New FilterConsumerInitEventArgs()

                ' Set the field names.
                filterConsumerInitArgs.FieldList = _filterFieldNames
                filterConsumerInitArgs.FieldDisplayList = _filterFieldDisplayNames

                ' Fire the FilterConsumerInit event.
                RaiseEvent FilterConsumerInit(Me, filterConsumerInitArgs)
            End If
        End Sub
      
      ' Step #8: Override the GetInitEventArgs method.
      ' GetInitEventArgs() is called by the Web Part infrastructure 
      ' during the ASP.NET PreRender event to gather the 
      ' necessary information it needs to build the transformer dialog. 
      ' The transformer dialog is needed when connecting different 
      ' interfaces such as IRowProvider to ICellConsumer. The 
      ' transformer dialog allows the user to map the fields between 
      ' the interfaces. The GetInitEventArgs()method only needs to be 
      ' implemented for interfaces that can participate in a 
      ' transformer which are the following:
      ' ICellConsumer, IRowProvider, IFilterConsumer, 
      ' IParametersOutProvider, IParametersInConsumer.
      ' <param name="interfacename">Name of interface on which the Web 
      ' Part infrastructure is requesting information</param>
      ' <returns>An InitEventArgs object</returns>
      Public Overrides Function GetInitEventArgs(interfaceName As String) As InitEventArgs
         ' Check if this is my particular cell interface.
         If interfaceName = "MyFilterConsumerInterface" Then
            'Ensure that all of the Web Part's controls are created.
            'The _filterFieldNames and _filterFieldDisplayNames are set 
            ' during EnsureChildControls()
            EnsureChildControls()
            
            ' Create the FilterConsumerInitEventArgs object for the 
            ' FilterConsumerInit event.
            Dim filterConsumerInitArgs As New FilterConsumerInitEventArgs()
            
            ' Set the field names
            filterConsumerInitArgs.FieldList = _filterFieldNames
            filterConsumerInitArgs.FieldDisplayList = _filterFieldDisplayNames
            
            ' return the FilterConsumerInitEventArgs. 
            Return filterConsumerInitArgs
         Else
            Return Nothing
         End If
      End Function
      
      ' Step #9: Implement the SetFilter event handler.
      ' The connected provider part will call this method during its 
      ' PartCommunicationMain phase
      ' to set the filter on the consumer Web Part.
      ' <param name="sender">Provider Web Part</param>
      ' <param name="SetFilterArgs">The args passed by the 
      ' Provider</param>
      Public Sub SetFilter(sender As Object, setFilterEventArgs As SetFilterEventArgs) Implements IFilterConsumer.SetFilter
         ' Ensure that all of the Web Part's controls are created.
         EnsureChildControls()
         
         ' Convert FilterExpression to the DataTable RowFilter syntax.
         If Not (setFilterEventArgs.FilterExpression Is Nothing) Then
            
            ' Parse the filter information.
            Dim values As String() = setFilterEventArgs.FilterExpression.Split(New [Char]() {"&"c})
            If values.Length > 1 Then
               Dim j As Integer = 1 'counts the number of Field/Value pairs
               Dim filterField As String = String.Empty
               Dim filterValue As String = String.Empty
               Dim filterAnd As String = " AND "
               _rowFilterExpression = String.Empty
               
               Dim i As Integer
               For i = 0 To values.Length - 1
                  ' Clear values.
                  filterField = String.Empty
                  filterValue = String.Empty
                  
                  ' Create label portion of name/value pairs.
                  Dim currField, currValue As String
                  currField = FieldLabel + j.ToString() + "="
                  currValue = ValueLabel + j.ToString() + "="
                  j += 1
                  
                  ' Extract just the field name by replacing the rest 
                  ' of the string with string.Empty.
                  filterField = filterField + values(i).Replace(currField, String.Empty)
                  
                  ' Move to next item in the array which is the value 
                  ' component.
                  i += 1
                  
                  ' Extract just the Value by replacing the rest of the 
                  ' string with string.Empty.
                  filterValue = filterValue + values(i).Replace(currValue, String.Empty)
                  
                  ' Contruct the row filter expression.
                  _rowFilterExpression += filterField + "=" + "'" + filterValue + "'" + filterAnd
               Next i 
               ' Trim Off the trailing 'And'.
               If _rowFilterExpression.Length <> 0 Then
                  _rowFilterExpression = _rowFilterExpression.Substring(0, _rowFilterExpression.Length - filterAnd.Length)
               End If 
               ' Store _rowFilterExpression for use by NoFilter event.
               _cachedRowFilter.Text = _rowFilterExpression
            End If
         End If
      End Sub
      
      ' Step #10: Implement the ClearFilter event handler.
      ' The connected provider part will call this method during its 
      ' PartCommunicationMain phase
      ' to remove the filter on the consumer Web Part.
      ' <param name="sender">Provider Web Part</param>
      ' <param name="eventArgs">The Event Arguments</param>
      Public Sub ClearFilter(sender As Object, eventArgs As EventArgs) Implements IFilterConsumer.ClearFilter
         ' Ensure that all of the Web Part's controls are created.
         EnsureChildControls()
         
         ' Clear the filter on the DataTable.
         _rowFilterExpression = String.Empty
         
         ' Clear out the cached row filter expression.
         _cachedRowFilter.Text = String.Empty
      End Sub
      
      ' Step #11: Implement NoFilter event handler.
      ' The connected provider part will call this method during its 
      ' PartCommunicationMain phase to indicate there is no change in 
      ' the filter. This allows the consumer part to 
      ' display its cached data instead of recalculating the filter 
      ' expression or potentially hitting a database again. 
      ' <param name="sender">Provider Web Part</param>
      ' <param name="eventArgs">The Event Arguments</param>
      Public Sub NoFilter(sender As Object, eventArgs As EventArgs) Implements IFilterConsumer.NoFilter
         ' Ensure that all of the Web Part's controls are created.
         EnsureChildControls()
         
         ' No change in the filter so use cached _cachedRowFilter.
         _rowFilterExpression = _cachedRowFilter.Text
      End Sub
      
      Protected Overrides Sub RenderWebPart(output As HtmlTextWriter)
         'Check for connection interface registration error
         If _registrationErrorOccurred Then
            output.Write(_registrationErrorMsg)
            Return
         End If
         
         ' Ensure that all of the Web Part's controls are created.
         EnsureChildControls()
         
         ' Row filter expression supplied by provider. 
         output.RenderBeginTag(HtmlTextWriterTag.B)
         output.Write((_convertedRowFilterLabel + ": "))
         output.RenderEndTag()
         output.Write(_rowFilterExpression)
         
         ' Line break.
         output.RenderBeginTag(HtmlTextWriterTag.Br)
         output.RenderEndTag()
         
         ' Set filter.
         CType(_dataGrid.DataSource, DataTable).DefaultView.RowFilter = _rowFilterExpression
         _dataGrid.DataBind()
         
         ' Render the DataGrid control.
         _dataGrid.RenderControl(output)
         
         'Line break.
         output.RenderBeginTag(HtmlTextWriterTag.Br)
         output.RenderEndTag()
         
         ' Hidden Row Filter TextBox stores _rowFilterExpression.
         _cachedRowFilter.RenderControl(output)
         
         ' Check if connected.
         If _connected Then
            ' Render connected Web Part title.
            output.Write((_connectedWebPartLabel + ": "))
            output.RenderBeginTag(HtmlTextWriterTag.I)
            output.Write(_connectedWebPartTitle)
            output.RenderEndTag()
            output.Write("<br>")
         Else
            ' The Web Part isn't connected.
            output.Write(_notConnectedMsg)
         End If
      End Sub
      
      ' Create Web Part user interface controls.
      Protected Overrides Sub CreateChildControls()
         ' Create hidden textbox to store _rowFilterExpression.
         _cachedRowFilter = New TextBox()
         _cachedRowFilter.ID = "CachedRowFilter"
         _cachedRowFilter.Visible = False
         Controls.Add(_cachedRowFilter)
         
         ' Create the DataGrid.
         _dataGrid = New DataGrid()
         _dataGrid.ID = "DataGrid"
         
         ' Create the DataTable.
         Dim dataTable As New DataTable()
         
         ' Add four column objects to the table.
         Dim idColumn As New DataColumn()
         idColumn.DataType = System.Type.GetType("System.Int32")
         idColumn.ColumnName = "ID"
         idColumn.Caption = "ID"
         idColumn.AutoIncrement = True
         dataTable.Columns.Add(idColumn)
         
         Dim Product As New DataColumn()
         Product.DataType = System.Type.GetType("System.String")
         Product.ColumnName = "Product"
         Product.Caption = "Product"
         dataTable.Columns.Add(Product)
         
         Dim productCategory As New DataColumn()
         productCategory.DataType = System.Type.GetType("System.String")
         productCategory.ColumnName = "Category"
         productCategory.Caption = "Category"
         dataTable.Columns.Add(productCategory)
         
         Dim Stock As New DataColumn()
         Stock.DataType = System.Type.GetType("System.Int32")
         Stock.ColumnName = "Stock"
         Stock.Caption = "Stock"
         dataTable.Columns.Add(Stock)
         
         ' Once a table has been created, use the NewRow method to 
         ' create a DataRow.
         Dim dataRow As DataRow
         
         ' Add first row to collection.
         dataRow = dataTable.NewRow()
         dataRow("Product") = "Aniseed Syrup"
         dataRow("Category") = "Condiments"
         dataRow("Stock") = 25
         dataTable.Rows.Add(dataRow)
         
         ' Add a second row.
         dataRow = dataTable.NewRow()
         dataRow("Product") = "Vegie-spread"
         dataRow("Category") = "Condiments"
         dataRow("Stock") = 10
         dataTable.Rows.Add(dataRow)
         
         ' Add a third row.
         dataRow = dataTable.NewRow()
         dataRow("Product") = "Outback Lager"
         dataRow("Category") = "Beverages"
         dataRow("Stock") = 30
         dataTable.Rows.Add(dataRow)
         
         ' Add a fourth row.
         dataRow = dataTable.NewRow()
         dataRow("Product") = "Boston Crab Meat"
         dataRow("Category") = "Seafood"
         dataRow("Stock") = 10
         dataTable.Rows.Add(dataRow)
         
         ' Add a fifth row.
         dataRow = dataTable.NewRow()
         dataRow("Product") = "Tofu"
         dataRow("Category") = "Produce"
         dataRow("Stock") = 41
         dataTable.Rows.Add(dataRow)
         
         ' Set the DataGrid's DataSource.
         _dataGrid.DataSource = dataTable
         
         ' Format the DataGrid.
         _dataGrid.HeaderStyle.Font.Bold = True
         _dataGrid.HeaderStyle.ForeColor = Color.DarkBlue
         _dataGrid.HeaderStyle.HorizontalAlign = HorizontalAlign.Center
         _dataGrid.AlternatingItemStyle.BackColor = Color.Beige
         
         _dataGrid.DataBind()
         Controls.Add(_dataGrid)
         
         ' Set the DataTable field names.
         ' This information will be passed to the Provider Web Part 
         ' when firing the FilterConsumerInit event.
         Dim columnCount As Integer = dataTable.Columns.Count
         _filterFieldNames = New String(columnCount-1) {}
         _filterFieldDisplayNames = New String(columnCount-1) {}
         
         Dim i As Integer
         For i = 0 To columnCount - 1
            _filterFieldNames(i) = dataTable.Columns(i).ColumnName
            _filterFieldDisplayNames(i) = dataTable.Columns(i).Caption
         Next i
      End Sub
   End Class
End Namespace
// Common .NET required namespaces
using System;
using System.ComponentModel;
using System.Web.UI;

// Web Part required namespaces
using Microsoft.SharePoint.WebPartPages;
using System.Xml.Serialization;
using System.Web.UI.WebControls;

// Code Access Security namespaces
using System.Security;
using Microsoft.SharePoint.Utilities;

// DataGrid and user interface namespaces
using System.Data;
using System.Drawing;

// Step #1: Reference the Communication namespace.
using Microsoft.SharePoint.WebPartPages.Communication;

namespace ConnectionCodeSamples
{
    // Step #2: Implement the IFilterConsumer interface.
    public class ServerSideFilterConsumer : WebPart, IFilterConsumer
    {    
        // Step #3: Declare the IFilterConsumer event.
        // Because this class implements the IFilterConsumer interface, 
        // it must declare the interface member FilterConsumerInit. 
        
        public event FilterConsumerInitEventHandler FilterConsumerInit;

        // Declare variables for keeping track of connection state.
        private bool _connected = false;
        private string _connectedWebPartTitle = string.Empty;
        private string _registrationErrorMsg = "An error has occurred trying to register your connection interfaces.";
        private bool _registrationErrorOccurred = false;
        private string _notConnectedMsg = "NOT CONNECTED. To filter this Web Part connect it to a Filter or Row Provider Web Part.";

        // Declare variables for Web Part user interface.
        private string _connectedWebPartLabel = "Connected to Web Part";
        private string _convertedRowFilterLabel ="Converted Row Filter";
        private DataGrid _dataGrid;
        private string _rowFilterExpression = string.Empty;
        private TextBox _cachedRowFilter;

        // Declare variables for filter field information.
        private string[] _filterFieldNames;
        private string[] _filterFieldDisplayNames;
        private string FieldLabel = "FilterField";
        private string ValueLabel = "FilterValue";

        // Step #4: Override EnsureInterfaces method and call RegisterInterface method.
        // EnsureInterfaces() is called by the Web Part infrastructure 
        // during the ASP.NET PreRender event 
        // and allows the part to register all of its connection 
        // interfaces.

        public override void EnsureInterfaces()
        {
            // If your Web Part is installed in the bin directory and 
            // the Code Access Security (CAS) setting doesn't 
            // allow Web Part Connections, an exception will be thrown. 
            // To allow your Web Part to behave 
            // well and continue working, a try/catch block should be 
            // used when attempting to register interfaces.
            // Web Part Connections will only work if the level 
            // attribute of the <trust> tag in the 
            // web.config file is set to WSS_Minimal, WSS_Medium, or 
            // Full. By default a new SharePoint site
            // is installed with the trust level set to WSS_Minimal.
            try
            {
                // Register the IFilterConsumer Interface
                // <param name="interfaceName">Friendly name of the 
                // interface that is being implemented.</param>
                // <param name="interfaceType">Specifies which 
                // interface is being implemented.</param>
                // <param name="maxConnections">Defines how many times 
                // this interface can be connected.</param>
                // <param name="runAtOptions">Determines where the 
                // interface can run.</param>
                // <param name="interfaceObject">Reference to the 
                // object that is implementing this interface.</param>
                // <param name="interfaceClientReference">Name used to 
                // reference the interface on the client. 
                // This is a server side example so the value is set to 
                // empty string.</param>
                // <param name="menuLabel">Label for the interface 
                // which appears in the UI</param>
                // <param name="description">Description of the 
                // interface which appears in the UI</param>
                // <param name="allowCrossPageConnection">Specifies if 
                // the interface can connect to a Web Part
                // on a different page. This is an optional parameter 
                // with a default of false. Note that only some 
                // server side interfaces are allowed to connect across 
                // pages by the Web Part infrastructure. 
                // The IFilterConsumer interface is allowed to connect 
                // across pages.</param>
                RegisterInterface("MyFilterConsumerInterface",                 //InterfaceName    
                    InterfaceTypes.IFilterConsumer,                            //InterfaceType
                    WebPart.LimitOneConnection,                                //MaxConnections
                    ConnectionRunAt.Server,                                    //RunAtOptions
                    this,                                                      //InterfaceObject
                    "",                                                        //InterfaceClientReference
                    "Consume Filter From",                                     //MenuLabel
                    "Consumes a Filter from another Web Part.",                //Description
                    true);                                                     //allowCrossPageConnection
            }
            catch(SecurityException se)
            {
                _registrationErrorOccurred = true;
            }
        }

        // Step #5: Override CanRunAt method.
        // CanRunAt() is called by the Web Part infrastructure during 
        // the ASP.NET PreRender event
        // to determine where the Web Part can run based on its current 
        // configuration.
        public override ConnectionRunAt CanRunAt()
        {
            // This Web Part can run on the server.
            return ConnectionRunAt.Server;
        }

        // Step #6: Override PartCommunicationConnect method.
        // PartCommunicationConnect() is called by the Web Part 
        // infrastructure to notify the Web Part that it
        // is connected during the ASP.NET PreRender event. Relevant 
        // information is passed to the part such as 
        // the interface it is connected over, the Web Part it is being 
        // connected to, and where the part will be running, 
        // either client or server side. 
        // <param name="interfaceName">Friendly name of the interface 
        // that is being connected</param>
        // <param name="connectedPart">Reference to the other Web Part 
        // that is being connected to</param>
        // <param name="connectedInterfaceName">Friendly name of the 
        // interface on the other Web Part</param>
        // <param name="runAt">Where the interface should 
        // execute</param>
        public override void PartCommunicationConnect(string interfaceName,
            WebPart connectedPart,
            string connectedInterfaceName,
            ConnectionRunAt runAt)
        {
            //Check if this is my particular Filter interface
            if (interfaceName == "MyFilterConsumerInterface")
            {
                //Keep track of the Connection
                _connected = true;
                _connectedWebPartTitle = SPEncode.HtmlEncode(connectedPart.Title);
            }
        }

        // Step #7: Override PartCommunicationInit method.
        // PartCommunicationInit() is called by the Web Part 
        // infrastructure during the ASP.NET PreRender event
        // to allow the part to pass initialization information to the 
        // other connected parts.
        // It is important to always pass initialization information. 
        // Some parts may not behave properly if this initialization 
        // information is not received.
        public override void PartCommunicationInit()
        {
            // If the connection wasn't actually formed then don't want 
            // to send Init event
            if(_connected)
            {
                // Ensure that all of the Web Part's controls are 
                // created
                // The _filterFieldNames and _filterFieldDisplayNames 
                // are set during EnsureChildControls()
                EnsureChildControls();

                // If there is a listener, fire the FilterConsumerInit 
                // event
                if (FilterConsumerInit != null)
                {
                    // Create the FilterConsumerInitEventArgs object 
                    // for the FilterConsumerInit event.
                    FilterConsumerInitEventArgs filterConsumerInitArgs = new FilterConsumerInitEventArgs();
                    
                    // Set the field names.
                    filterConsumerInitArgs.FieldList = _filterFieldNames;
                    filterConsumerInitArgs.FieldDisplayList = _filterFieldDisplayNames;
                    
                    // Fire the FilterConsumerInit event.
                    FilterConsumerInit(this, filterConsumerInitArgs);
                }
            }
        }

        // Step #8: Override the GetInitEventArgs method.
        // GetInitEventArgs() is called by the Web Part infrastructure 
        // during the ASP.NET PreRender event to gather the 
        // necessary information it needs to build the transformer 
        // dialog. The transformer dialog is needed when connecting 
        // different interfaces such as IRowProvider
        // to ICellConsumer. The transformer dialog allows the user to 
        // map the fields between the interfaces. The 
        // GetInitEventArgs()method only needs to be implemented for 
        // interfaces that can participate in a transformer, which are 
        // the following:
        // ICellConsumer, IRowProvider, IFilterConsumer, 
        // IParametersOutProvider, IParametersInConsumer.
        // <param name="interfacename">Name of interface on which the 
        // Web Part infrastructure is requesting information</param>
        // <returns>An InitEventArgs object</returns>
        public override InitEventArgs GetInitEventArgs(string interfaceName)
        {
            // Check if this is my particular cell interface.
            if (interfaceName == "MyFilterConsumerInterface")
            {
                // Ensure that all of the Web Part's controls are 
                // created.
                //The _filterFieldNames and _filterFieldDisplayNames 
                // are set during EnsureChildControls()
                EnsureChildControls();

                // Create the FilterConsumerInitEventArgs object for 
                // the FilterConsumerInit event.
                FilterConsumerInitEventArgs filterConsumerInitArgs = new FilterConsumerInitEventArgs();
                    
                // Set the field names
                filterConsumerInitArgs.FieldList = _filterFieldNames;
                filterConsumerInitArgs.FieldDisplayList = _filterFieldDisplayNames;
                    
                // return the FilterConsumerInitEventArgs. 
                return(filterConsumerInitArgs);
            }
            else
            {
                return(null);
            }
        }

        // Step #9: Implement the SetFilter event handler.
        // The connected provider part will call this method during its 
        // PartCommunicationMain phase
        // to set the filter on the consumer Web Part.
        // <param name="sender">Provider Web Part</param>
        // <param name="SetFilterArgs">The args passed by the 
        // Provider</param>
        public void SetFilter(object sender, SetFilterEventArgs setFilterEventArgs)
        {
            // Ensure that all of the Web Part's controls are created.
            EnsureChildControls();

            // Convert FilterExpression to the DataTable RowFilter 
            // syntax.
            if(setFilterEventArgs.FilterExpression != null)
            {
                
                // Parse the filter information.
                string[] values = setFilterEventArgs.FilterExpression.Split(new Char[] {'&'});
                if (values.Length > 1)
                {
                    int j = 1;  //counts the number of Field/Value pairs
                    string filterField = string.Empty;
                    string filterValue = string.Empty;
                    string filterAnd = " AND ";
                    _rowFilterExpression = string.Empty;

                    for(int i=0; i < values.Length; i++)
                    {
                        // Clear values.
                        filterField = string.Empty;
                        filterValue = string.Empty;

                        // Create label portion of name/value pairs.
                        string currField, currValue;
                        currField = FieldLabel + j + "=";
                        currValue = ValueLabel + j + "=";
                        j++;  
                    
                        // Extract just the field name by replacing
                        // the rest of the string with string.Empty.
                        filterField = filterField + values[i].Replace(currField, string.Empty);
                    
                        // Move to next item in the array which is 
                        // the value component.
                        i++;
                
                        // Extract just the Value by replacing the 
                        // rest of the string with string.Empty.
                        filterValue = filterValue + values[i].Replace(currValue, string.Empty);

                        // Contruct the row filter expression.
                        _rowFilterExpression += filterField + "=" + "'" + filterValue + "'" + filterAnd;

                    }
                    // Trim Off the trailing 'And'.
                    if (_rowFilterExpression.Length != 0)
                        _rowFilterExpression = _rowFilterExpression.Substring(0,_rowFilterExpression.Length - filterAnd.Length);

                    // Store _rowFilterExpression for use by 
                    // NoFilter event.
                    _cachedRowFilter.Text = _rowFilterExpression;
                }
            }
        }

        // Step #10: Implement ClearFilter event handler.
        // The connected provider part will call this method during 
        // its PartCommunicationMain phase
        // to remove the filter on the consumer Web Part.
        // <param name="sender">Provider Web Part</param>
        // <param name="eventArgs">The Event Arguments</param>
        public void ClearFilter(object sender, EventArgs eventArgs)
        {
            // Ensure that all of the Web Part's controls are created.
            EnsureChildControls();

            // Clear the filter on the DataTable.
            _rowFilterExpression = string.Empty;

            // Clear out the cached row filter expression.
            _cachedRowFilter.Text = string.Empty;
        }

        // Step #11: Implement NoFilter event handler.
        // The connected provider part will call this method during 
        // its PartCommunicationMain phase to indicate there is no 
        // change in the filter. This allows the consumer part to 
        // display its cached data instead of recalculating the 
        // filter expression or potentially hitting a database again. 
        // <param name="sender">Provider Web Part</param>
        // <param name="eventArgs">The Event Arguments</param>
        public void NoFilter(object sender, EventArgs eventArgs)
        {
            // Ensure that all of the Web Part's controls are created.
            EnsureChildControls();

            // No change in the filter so use cached _cachedRowFilter.
            _rowFilterExpression = _cachedRowFilter.Text;

        }

        protected override void RenderWebPart(HtmlTextWriter output)
        {
            //Check for connection interface registration error
            if (_registrationErrorOccurred)
            {
                output.Write(_registrationErrorMsg);
                return;
            }

            // Ensure that all of the Web Part's controls are created.
            EnsureChildControls();

            // Row filter expression supplied by provider. 
            output.RenderBeginTag(HtmlTextWriterTag.B);
            output.Write(_convertedRowFilterLabel + ": ");
            output.RenderEndTag();
            output.Write(_rowFilterExpression);

            // Line break.
            output.RenderBeginTag(HtmlTextWriterTag.Br);
            output.RenderEndTag();

            // Set filter.
            ((DataTable)_dataGrid.DataSource).DefaultView.RowFilter = _rowFilterExpression;
            _dataGrid.DataBind();

            // Render the DataGrid control.
            _dataGrid.RenderControl(output);

            //Line break.
            output.RenderBeginTag(HtmlTextWriterTag.Br);
            output.RenderEndTag();

            // Hidden Row Filter TextBox stores _rowFilterExpression.
            _cachedRowFilter.RenderControl(output);

            // Check if connected.
            if(_connected)
            {
                // Render connected Web Part title.
                output.Write(_connectedWebPartLabel + ": ");
                output.RenderBeginTag(HtmlTextWriterTag.I);
                output.Write(_connectedWebPartTitle);
                output.RenderEndTag();
                output.Write("<br>");
            }
            else
            {
                // The Web Part isn't connected.
                output.Write(_notConnectedMsg);
            }
        }

        // Create Web Part user interface controls.
        protected override void CreateChildControls()
        {
            // Create hidden textbox to store _rowFilterExpression.
            _cachedRowFilter = new TextBox();
            _cachedRowFilter.ID = "CachedRowFilter";
            _cachedRowFilter.Visible = false;
            Controls.Add(_cachedRowFilter);

            // Create the DataGrid.
            _dataGrid = new DataGrid();
            _dataGrid.ID = "DataGrid";

            // Create the DataTable.
            DataTable dataTable = new DataTable();

            // Add four column objects to the table.
            DataColumn idColumn = new  DataColumn();
            idColumn.DataType = System.Type.GetType("System.Int32");
            idColumn.ColumnName = "ID";
            idColumn.Caption = "ID";
            idColumn.AutoIncrement = true;
            dataTable.Columns.Add(idColumn);

            DataColumn Product = new DataColumn();
            Product.DataType = System.Type.GetType("System.String");
            Product.ColumnName = "Product";
            Product.Caption = "Product";
            dataTable.Columns.Add(Product);

            DataColumn productCategory = new DataColumn();
            productCategory.DataType = System.Type.GetType("System.String");
            productCategory.ColumnName = "Category";
            productCategory.Caption = "Category";
            dataTable.Columns.Add(productCategory);

            DataColumn Stock = new DataColumn();
            Stock.DataType = System.Type.GetType("System.Int32");
            Stock.ColumnName = "Stock";
            Stock.Caption = "Stock";
            dataTable.Columns.Add(Stock);

            // Once a table has been created, use the NewRow method 
            // to create a DataRow.
            DataRow dataRow;

            // Add first row to collection.
            dataRow = dataTable.NewRow();
            dataRow["Product"] = "Aniseed Syrup";
            dataRow["Category"] = "Condiments";
            dataRow["Stock"] = 25;
            dataTable.Rows.Add(dataRow);

            // Add a second row.
            dataRow = dataTable.NewRow();
            dataRow["Product"] = "Vegie-spread";
            dataRow["Category"] = "Condiments";
            dataRow["Stock"] = 10;
            dataTable.Rows.Add(dataRow);

            //Add a third row.
            dataRow = dataTable.NewRow();
            dataRow["Product"] = "Outback Lager";
            dataRow["Category"] = "Beverages";
            dataRow["Stock"] = 30;
            dataTable.Rows.Add(dataRow);

            // Add a fourth row.
            dataRow = dataTable.NewRow();
            dataRow["Product"] = "Boston Crab Meat";
            dataRow["Category"] = "Seafood";
            dataRow["Stock"] = 10;
            dataTable.Rows.Add(dataRow);

            // Add a fifth row.
            dataRow = dataTable.NewRow();
            dataRow["Product"] = "Tofu";
            dataRow["Category"] = "Produce";
            dataRow["Stock"] = 41;
            dataTable.Rows.Add(dataRow);

            // Set the DataGrid's DataSource.
            _dataGrid.DataSource = dataTable;
            
            // Format the DataGrid.
            _dataGrid.HeaderStyle.Font.Bold = true;
            _dataGrid.HeaderStyle.ForeColor = Color.DarkBlue;
            _dataGrid.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
            _dataGrid.AlternatingItemStyle.BackColor = Color.Beige;

            _dataGrid.DataBind();
            Controls.Add(_dataGrid);

            // Set the DataTable field names.
            //This information will be passed to the Provider Web Part 
            // when firing the FilterConsumerInit event.
            int columnCount = dataTable.Columns.Count;
            _filterFieldNames = new string[columnCount];
            _filterFieldDisplayNames = new string[columnCount];

            for(int i = 0; i < columnCount; i++)
            {
                _filterFieldNames[i] = dataTable.Columns[i].ColumnName;
                _filterFieldDisplayNames[i] = dataTable.Columns[i].Caption;
            }
        }
    }
}

See Also

Reference

IFilterConsumer Members

Microsoft.SharePoint.WebPartPages.Communication Namespace