Compartilhar via


IFilterProvider Interface

NOTE: This API is now obsolete.

Used to communicate with a Web Part that implements IFilterConsumer interface to provide filter information to the consumer.

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 IFilterProvider
'Usage
Dim instance As IFilterProvider
[ObsoleteAttribute("Use System.Web.UI.WebControls.WebParts.IWebPartParameters instead")]
public interface IFilterProvider

Remarks

The IFilterProvider interface should be used with Web Parts that need to pass a collection of filter values to a consuming Web Part. The events of IFilterProvider were designed for the purpose of setting and clearing multiple filter values. It can be used in scenarios where the consumer part was designed with an understanding of the type of data passed by the provider part. Because the IFilterProvider part can receive initialization parameters from an IFilterConsumer part the IFilterProvider part can dynamically change its user interface to better fit the needs of the consumer part. The IFilterProvider can only be connected to the IFilterConsumer interface. When connecting the IFilterProvider to IFilterConsumer, this is a direct connection so no transformer dialog box will be displayed. Also, server-side implementations of IFilterProvider can be connected to parts on a different page by an HTML editor compatible with Microsoft SharePoint Foundation, such as Microsoft SharePoint Designer.

Examples

The following code example shows a server-side IFilterProvider Web Part. It can be connected to another Web Part which implements the IFilterConsumer interface on the server. This IFilterProvider Web Part will dynamically generate an input form based on the columns sent to it by the IFilterConsumer Web Part. The IFilterProvider Web Part can be used to pass filter values to the IFilterConsumer Web Part.

There are 8 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

'Step #1: Make a reference to the Communication namespace
Imports Microsoft.SharePoint.WebPartPages.Communication

Namespace ConnectionCodeSamples
   'Step #2: Inherit from the WebPart base class and implement the IFilterProvider interface.
   
   Public Class ServerSideFilterProvider
      Inherits WebPart
      Implements IFilterProvider

      ' Step #3: Declare the IFilterProvider events.
      ' Because this class implements the IFilterProvider interface, it 
      ' must declare the interface members SetFilter, ClearFilter, 
      ' NoFilter. 
      Public Event SetFilter As SetFilterEventHandler Implements 
         IFilterProvider.SetFilter
      Public Event ClearFilter As ClearFilterEventHandler Implements 
         IFilterProvider.ClearFilter
      Public Event NoFilter As NoFilterEventHandler Implements 
         IFilterProvider.NoFilter
      
      ' Declare variables for keeping track of the 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 use this 
         Web Part connect it to a Filter Consumer Web Part."
      
      ' Declare variables for the Web Part user interface.
      Private _connectedWebPartLabel As String = "Connected to Web 
         Part"
      Private _filterExpressionLabel As String = "FilterExpression sent"
      Private _fieldListKey As String = "ProviderFieldList" 'Key for 
         ViewState StateBag
      Private _filterExpression As String = String.Empty
      Private _setFilterButton As Button
      Private _clearFilterButton As Button
      Private _noFilterButton As Button
      Private _filterInputs() As TextBox
      
      ' Declare variables for tracking whether the button was clicked.
      Private _setFilterClicked As Boolean = False
      Private _clearFilterClicked As Boolean = False
      Private _noFilterClicked As Boolean = False
      
      ' Declare variables for filter information.
      Private _fieldList As String() = Nothing
      Private _fieldDisplayList As String() = Nothing
      Private FieldLabel As String = "FilterField"
      Private ValueLabel As String = "FilterValue"
     
      ' Step #4: Implement EnsureInterfaces method and call 
      ' RegisterInterface method.
      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 IFilterProvider 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 IFilterProvider interface is allowed to connect 
            ' across pages.</param>
            RegisterInterface("MyFilterProviderInterface", 
               InterfaceTypes.IFilterProvider, 
               WebPart.LimitOneConnection, ConnectionRunAt.Server, 
               Me, "", "Provide Filter To", "Provides a Filter to a 
               consumer Web Part.", True) 

         Catch se As SecurityException
            _registrationErrorOccurred = True
         End Try
      End Sub
      
      ' Step #5: Override the CanRunAt() method.
      ' The CanRunAt method 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.
      ' The PartCommunicationConnect method 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)
         ' Keep track of whether the Web Part is connected.
         If interfaceName = "MyFilterProviderInterface" Then
            _connected = True
            _connectedWebPartTitle = SPEncode.HtmlEncode(connectedPart.Title)
         End If
      End Sub
      
      ' Step #7: Override the PartCommunicationMain() method.
      ' The PartCommunicationMain method is called by the Web Part 
      ' infrastructure on the client during the ASP.NET PreRender
      ' event to allow the part to pass its primary data to the other 
      ' connected parts.
      ' It is important to always fire either the SetFilter, NoFilter, 
      ' or ClearFilter event. Some parts may not behave properly 
      ' if they are left waiting for this information.
      ' SetFilter should be fired to send the filter expression.
      ' NoFilter should be fired to indicate that there is no change in 
      ' the filter expression. 
      ' ClearFilter should be fired to indicate that the filter should 
      ' be removed.
      Public Overrides Sub PartCommunicationMain()
            ' Ensure that all of the Web Part's controls are created.
            EnsureChildControls()

            ' Check if connected.
            If _connected Then
                ' Check which button was clicked.
                If _setFilterClicked = True Then
                    ' Create the SetFilterEventArgs object for the 
                    ' SetFilter event.
                    Dim setFilterEventArgs As New SetFilterEventArgs()

                    ' Create the filter expression.
                    Dim eIndex As Integer = 1
                    Dim filterExpression As String = String.Empty
                    Dim index As Integer
                    For index = 0 To _fieldList.Length - 1
                        ' This filter expression syntax should be used 
                        ' with SharePoint Lists
                        ' and other Microsoft Web Parts that support 
                        ' the IFilterConsumer interface.
                        If _filterInputs(index).Text <> String.Empty 
                        Then
                            filterExpression += FieldLabel + 
                               eIndex.ToString() + "=" + 
                               _fieldList(index) + "&"
                            filterExpression += ValueLabel + 
                               eIndex.ToString() + "=" + 
                               _filterInputs(index).Text + "&"
                            eIndex += 1
                        End If
                    Next index

                    ' Trim Off Trailing '&'
                    If filterExpression.Length <> 0 Then
                        filterExpression = 
                           filterExpression.Substring(0, 
                           filterExpression.Length - 1)
                    End If
                    ' Set the FilterExpression property on the 
                    ' SetFilterEventArgs object.
                    setFilterEventArgs.FilterExpression = 
                       filterExpression

                    ' Set the _filterExpression variable for display in 
                    ' the user interface.
                    _filterExpression = filterExpression

                    ' Fire the event.
                    RaiseEvent SetFilter(Me, setFilterEventArgs)
                    _setFilterClicked = False

                ElseIf _clearFilterClicked = True Then
                    RaiseEvent ClearFilter(Me, New EventArgs())
                    _clearFilterClicked = False

                    ' Clear out values in input text boxes.
                    If Not (_filterInputs Is Nothing) Then
                        Dim index As Integer
                        For index = 0 To _filterInputs.Length - 1
                            _filterInputs(index).Text = String.Empty
                        Next index
                    End If
                ElseIf _noFilterClicked = True Then
                    RaiseEvent NoFilter(Me, New EventArgs())
                    _noFilterClicked = False
                Else
                    RaiseEvent NoFilter(Me, New EventArgs())
                End If
            End If
        End Sub
      
      ' Step #8: Implement the FilterConsumerInit() method.
      ' The connected consumer part will call this method during its 
      ' PartCommunicationInit phase
      ' to pass initialization information to the provider Web Part. 
      ' The column names from the consumer Web Part are passed in. In 
      ' this example, these values are used to dynamcially 
      ' generate the input text boxes in the provider Web Part.
      ' <param name="sender">Consumer Web Part</param>
      ' <param name="filterConsumerInitArgs">The args passed by the 
      ' Consumer</param>
      Public Sub FilterConsumerInit(sender As Object, 
         filterConsumerInitEventArgs As FilterConsumerInitEventArgs) 
         Implements IFilterProvider.FilterConsumerInit
         If Not (filterConsumerInitEventArgs.FieldList Is Nothing) Then
            _fieldList = filterConsumerInitEventArgs.FieldList
         Else
            _fieldList = Nothing
         End If 
         If Not (filterConsumerInitEventArgs.FieldDisplayList Is 
            Nothing) Then
            _fieldDisplayList = filterConsumerInitEventArgs.FieldDisplayList
         Else
            _fieldDisplayList = Nothing
         End If 
      End Sub
      
      Protected Overrides Sub RenderWebPart(output As HtmlTextWriter)
         ' Check for connection interface registration error.
         If _registrationErrorOccurred Then
            output.Write(_registrationErrorMsg)
            Return
         End If
         
         ' Check if connected.
         If _connected Then
            ' Line break.
            output.RenderBeginTag(HtmlTextWriterTag.Br)
            output.RenderEndTag()
            
            ' Generate input text boxes.
            Dim fieldName As String
            output.RenderBeginTag(HtmlTextWriterTag.Table)
            Dim index As Integer
            For index = 0 To _fieldDisplayList.Length - 1
               fieldName = _fieldDisplayList(index)
               
               output.RenderBeginTag(HtmlTextWriterTag.Tr)
               output.RenderBeginTag(HtmlTextWriterTag.Td)
               output.RenderBeginTag(HtmlTextWriterTag.B)
               output.Write((fieldName + ": "))
               output.RenderEndTag() 'End </B>
               output.RenderEndTag() 'End </TD>
               output.RenderBeginTag(HtmlTextWriterTag.Td)
               _filterInputs(index).RenderControl(output) 'Render text 
                  box
               output.RenderEndTag() 'End </TD>
               output.RenderEndTag() 'End </TR>
            Next index
            output.RenderEndTag() 'End <Table>
            ' Line break..
            output.RenderBeginTag(HtmlTextWriterTag.Br)
            output.RenderEndTag()
            
            ' Render the buttons.
            _setFilterButton.RenderControl(output)
            _clearFilterButton.RenderControl(output)
            _noFilterButton.RenderControl(output)
            
            ' Line break.
            output.RenderBeginTag(HtmlTextWriterTag.Br)
            output.RenderEndTag()
            
            ' Render the connected Web Part title.
            output.Write((_connectedWebPartLabel + ": "))
            output.RenderBeginTag(HtmlTextWriterTag.I)
            output.Write(_connectedWebPartTitle)
            output.RenderEndTag()
            
            ' Render the filter expression.
            output.Write("<br>")
            output.Write((_filterExpressionLabel + ": "))
            output.RenderBeginTag(HtmlTextWriterTag.I)
            output.Write(_filterExpression)
            output.RenderEndTag()
         
         Else
            ' The Web Part isn't connected.
            output.Write(_notConnectedMsg)
         End If
      End Sub
      
      ' Create the Web Part user interface controls.
      Protected Overrides Sub CreateChildControls()
         ' Create the buttons.
         _setFilterButton = New Button()
         _setFilterButton.ID = "SetFilterButton"
         _setFilterButton.Text = "Fire SetFilter"
         Controls.Add(_setFilterButton)
         
         _clearFilterButton = New Button()
         _clearFilterButton.ID = "ClearFilterButton"
         _clearFilterButton.Text = "Fire ClearFilter"
         Controls.Add(_clearFilterButton)
         
         _noFilterButton = New Button()
         _noFilterButton.ID = "NoFilterButton"
         _noFilterButton.Text = "Fire NoFilter"
         Controls.Add(_noFilterButton)
         
         ' Create the input field text boxes.
         ' The field names provided by the consumer Web Part needed to 
         ' be stored in a StateBag because 
         ' the page doesn't have the _fieldList in time after the first 
         ' postback to create the text box 
         ' controls and restore their view state.
         Dim providerFieldList As String = 
            CStr(ViewState(_fieldListKey))
         Dim fieldCount As Integer
         If providerFieldList Is Nothing AndAlso Not (_fieldList Is 
            Nothing) Then
                ' First postback of the page.
                ' Generate controls from _fieldList provided by 
                ' consumer Web Part.
                Dim FieldList As String() = _fieldList
                fieldCount = FieldList.Length

                _filterInputs = New TextBox(fieldCount - 1) {}

            Dim index As Integer
            For index = 0 To fieldCount - 1
               _filterInputs(index) = New TextBox()
               _filterInputs(index).ID = FieldList(index)
               Controls.Add(_filterInputs(index))
               
               ' Populate ViewState providerFieldList item to keep 
               ' track of field names.
               If index < fieldCount - 1 Then
                  ViewState(_fieldListKey) += 
                     FieldList(index).ToString() + ";"
               Else
                  ViewState(_fieldListKey) += 
                     FieldList(index).ToString()
               End If
            Next index
        ElseIf Not (providerFieldList Is Nothing) Then
                ' Subsequent postback of page. 
                ' Retrieve the field names from StateBag 
                ' providerFieldList
                'Need to parse the providerFieldList information to get 
                ' the individual fields
                Dim FieldList As String() = providerFieldList.Split(New 
                   [Char]() {";"c})
                fieldCount = FieldList.Length

                _filterInputs = New TextBox(fieldCount - 1) {}
            Dim index As Integer
            For index = 0 To fieldCount - 1
               _filterInputs(index) = New TextBox()
               _filterInputs(index).ID = FieldList(index)
               Controls.Add(_filterInputs(index))
            Next index
         End If
         
         ' Add event handler to listen for button's Click event.
         _setFilterClicked = False ' Initialize to false -- user hasn't 
            clicked yet
         AddHandler _setFilterButton.Click, AddressOf 
            SetFilterButtonClicked ' listen for Button's click event
         _clearFilterClicked = False ' Initialize to false -- user 
            hasn't clicked yet
         AddHandler _clearFilterButton.Click, AddressOf 
            ClearFilterButtonClicked ' listen for Button's click event
         _noFilterClicked = False ' Initialize to false -- user hasn't 
            clicked yet
         AddHandler _noFilterButton.Click, AddressOf 
            NoFilterButtonClicked ' listen for Button's click event
      End Sub
      
      ' The button OnClick event handler.
      ' <param name="sender">The Button object</param>
      ' <param name="e">The Event Arguments</param>
      Private Sub SetFilterButtonClicked(sender As Object, e As 
         EventArgs)
         _setFilterClicked = True 'user clicked button, set to true
      End Sub
      
      Private Sub ClearFilterButtonClicked(sender As Object, e As 
         EventArgs)
         _clearFilterClicked = True 'user clicked button, set to true
      End Sub
      
      Private Sub NoFilterButtonClicked(sender As Object, e As 
         EventArgs)
         _noFilterClicked = True 'user clicked button, set to true
      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;

//Step #1: Make a reference to the Communication namespace
using Microsoft.SharePoint.WebPartPages.Communication;


namespace ConnectionCodeSamples
{
    //Step #2: Inherit from the WebPart base class and implement the 
    // IFilterProvider interface.
    public class ServerSideFilterProvider : WebPart, IFilterProvider
    {    
        // Step #3: Declare the IFilterProvider events.
        // Because this class implements the IFilterProvider interface, 
        // it must declare the interface members SetFilter, 
        // ClearFilter, NoFilter. 
        public event SetFilterEventHandler SetFilter;
        public event ClearFilterEventHandler ClearFilter;
        public event NoFilterEventHandler NoFilter;        

        // Declare variables for keeping track of the 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 use this 
           Web Part connect it to a Filter Consumer Web Part.";

        // Declare variables for the Web Part user interface.
        private string _connectedWebPartLabel = "Connected to Web 
           Part";
        private string _filterExpressionLabel = "FilterExpression 
           sent";
        private string _fieldListKey = "ProviderFieldList"; 
        //Key for ViewState StateBag
        private string _filterExpression = string.Empty;
        private Button _setFilterButton;
        private Button _clearFilterButton;
        private Button _noFilterButton;
        private TextBox[] _filterInputs;
        
        // Declare variables for tracking whether the button was 
        // clicked.
        private bool _setFilterClicked = false;
        private bool _clearFilterClicked = false;
        private bool _noFilterClicked = false;

        // Declare variables for filter information.
        private string[] _fieldList  = null;
        private string[] _fieldDisplayList = null;
        private string FieldLabel = "FilterField";
        private string ValueLabel = "FilterValue";
        
        // Step #4: Implement EnsureInterfaces method and call 
        // RegisterInterface method.
        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 IFilterProvider 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 
                // tht 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 IFilterProvider interface is allowed to connect 
                // across pages.</param>
                RegisterInterface("MyFilterProviderInterface",                //InterfaceName    
                    InterfaceTypes.IFilterProvider,                           //InterfaceType
                    WebPart.LimitOneConnection,                               //MaxConnections
                    ConnectionRunAt.Server,                                   //RunAtOptions
                    this,                                                     //InterfaceObject
                    "",                                                       //InterfaceClientReference
                    "Provide Filter To",                                      //MenuLabel
                    "Provides a Filter to a consumer Web Part.",              //Description
                    true);                                                    //allowCrossPageConnection
            }
            catch(SecurityException se)
            {
                _registrationErrorOccurred = true;
            }
        }

        // Step #5: Override the CanRunAt() method.
        // The CanRunAt method 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 the PartCommunicationConnect() method.
        // The PartCommunicationConnect method 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 
        // conected 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)
        {
            // Keep track of whether the Web Part is connected.
            if (interfaceName == "MyFilterProviderInterface")
            {
                _connected = true;
                _connectedWebPartTitle = 
                   SPEncode.HtmlEncode(connectedPart.Title);
            }
        }

        // Step #7: Override the PartCommunicationMain() method.
        // The PartCommunicationMain method is called by the Web Part 
        // infrastructure on the client during the ASP.NET PreRender
        // event to allow the part to pass its primary data to the 
        // other connected parts.
        // It is important to always fire either the SetFilter, 
        // NoFilter, or ClearFilter event. Some parts
        // may not behave properly if they are left waiting for this 
        // information.
        // SetFilter should be fired to send the filter expression.
        // NoFilter should be fired to indicate that there is no change 
        // in the filter expression.
        // ClearFilter should be fired to indicate that the filter 
        // should be removed.
        public override void PartCommunicationMain()
        {
            // Ensure that all of the Web Part's controls are created.
            EnsureChildControls();

            // Check if connected.
            if(_connected)
            {
                // Check which button was clicked.
                if(_setFilterClicked == true)
                {
                    // If there is a listener, fire the SetFilter 
                    // event.
                    if (SetFilter != null)
                    {
                        // Create the SetFilterEventArgs object for the 
                        // SetFilter event.
                        SetFilterEventArgs setFilterEventArgs = new 
                           SetFilterEventArgs();

                        // Create the filter expression.
                        int eIndex = 1;
                        string filterExpression = string.Empty;
                        for (int index = 0; index < _fieldList.Length; 
                           index++)
                        {
                            // This filter expression syntax should be 
                            // used with SharePoint lists
                            // and other Microsoft Web Parts that 
                            // support the IFilterConsumer interface.
                            if (_filterInputs[index].Text != 
                               string.Empty)
                            {
                                filterExpression += FieldLabel + 
                                   eIndex.ToString() + "=" + 
                                   _fieldList[index] + "&";
                                filterExpression += ValueLabel + 
                                   eIndex.ToString()  + "=" + 
                                   _filterInputs[index].Text + "&";
                                eIndex++;
                            }
                        }

                        // Trim Off Trailing '&'
                        if (filterExpression.Length != 0)
                            filterExpression = filterExpression.Substring(0,filterExpression.Length - 1);

                        // Set the FilterExpression property on the 
                        // SetFilterEventArgs object.
                        setFilterEventArgs.FilterExpression = 
                           filterExpression;

                        // Set the _filterExpression variable for 
                        // display in the user interface.
                        _filterExpression = filterExpression;

                        // Fire the event.
                        SetFilter(this, setFilterEventArgs);

                        _setFilterClicked = false;
                    }
                }
                else if(_clearFilterClicked == true)
                {
                    // If there is a listener, fire the ClearFilter 
                    // event.
                    if (ClearFilter != null)
                    {
                        ClearFilter(this, new EventArgs());

                        _clearFilterClicked = false;

                        // Clear out values in input text boxes.
                        if (_filterInputs != null)
                        {
                            for (int index = 0; index < 
                               _filterInputs.Length; index++)
                               _filterInputs[index].Text = 
                               string.Empty;
                        }
                    }
                }
                else if(_noFilterClicked == true)
                {
                    // If there is a listener, fire the NoFilter event.
                    if (NoFilter != null)
                    {
                        NoFilter(this, new EventArgs());

                        _noFilterClicked = false;
                    }
                }
                else
                {
                    // If there is a listener, fire the NoFilter event.
                    if (NoFilter != null)
                    {
                        NoFilter(this, new EventArgs());
                    }
                }
            }
        }


        // Step #8: Implement the FilterConsumerInit() method.
        // The connected consumer part will call this method during its 
        // PartCommunicationInit phase
        // to pass initialization information to the provider Web Part. 
        // The column names from the
        // consumer Web Part are passed in. In this example, these 
        // values are used to dynamcially 
        // generate the input text boxes in the provider Web Part.
        // <param name="sender">Consumer Web Part</param>
        // <param name="filterConsumerInitArgs">The args passed by the 
        // Consumer</param>
        public void FilterConsumerInit(object sender, 
           FilterConsumerInitEventArgs filterConsumerInitEventArgs)
        {
            if(filterConsumerInitEventArgs.FieldList != null)
                _fieldList = filterConsumerInitEventArgs.FieldList;
            else
                _fieldList = null;

            if(filterConsumerInitEventArgs.FieldDisplayList != null)
                _fieldDisplayList = filterConsumerInitEventArgs.FieldDisplayList;
            else
                _fieldDisplayList = null;

        }

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

            // Check if connected.
            if(_connected)
            {
                // Line break.
                output.RenderBeginTag(HtmlTextWriterTag.Br);
                output.RenderEndTag();

                // Generate input text boxes.
                string fieldName;
                output.RenderBeginTag(HtmlTextWriterTag.Table);
                for (int index = 0; index < _fieldDisplayList.Length; 
                   index++)
                {
                    fieldName = _fieldDisplayList[index];
                    
                    output.RenderBeginTag(HtmlTextWriterTag.Tr);
                    output.RenderBeginTag(HtmlTextWriterTag.Td);
                    output.RenderBeginTag(HtmlTextWriterTag.B);
                    output.Write(fieldName + ": ");
                    output.RenderEndTag(); //End </B>
                    output.RenderEndTag(); //End </TD>

                    output.RenderBeginTag(HtmlTextWriterTag.Td);
                    _filterInputs[index].RenderControl(output); //Render text box
                    output.RenderEndTag(); //End </TD>
                    output.RenderEndTag(); //End </TR>
                }
                output.RenderEndTag(); //End <Table>

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

                // Render the buttons.
                _setFilterButton.RenderControl(output);
                _clearFilterButton.RenderControl(output);
                _noFilterButton.RenderControl(output);

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

                // Render the connected Web Part title.
                output.Write(_connectedWebPartLabel + ": ");
                output.RenderBeginTag(HtmlTextWriterTag.I);
                output.Write(_connectedWebPartTitle);
                output.RenderEndTag();

                // Render the filter expression.
                output.Write("<br>");
                output.Write(_filterExpressionLabel + ": ");
                output.RenderBeginTag(HtmlTextWriterTag.I);
                output.Write(_filterExpression);
                output.RenderEndTag();

            }
            else
            {
                // The Web Part isn't connected.
                output.Write(_notConnectedMsg);
            }
        }

        // Create the Web Part user interface controls.
        protected override void CreateChildControls()
        {
            // Create the buttons.
            _setFilterButton = new Button();
            _setFilterButton.ID = "SetFilterButton";
            _setFilterButton.Text = "Fire SetFilter";
            Controls.Add(_setFilterButton);

            _clearFilterButton = new Button();
            _clearFilterButton.ID = "ClearFilterButton";
            _clearFilterButton.Text = "Fire ClearFilter";
            Controls.Add(_clearFilterButton);

            _noFilterButton = new Button();
            _noFilterButton.ID = "NoFilterButton";
            _noFilterButton.Text = "Fire NoFilter";
            Controls.Add(_noFilterButton);

            // Create the input field text boxes.
            // The field names provided by the consumer Web Part needed 
            // to be stored in a StateBag because 
            // the page doesn't have the _fieldList in time after the 
            // first postback to create the text box 
            // controls and restore their view state.
            string providerFieldList = 
              (string)ViewState[_fieldListKey];
            int fieldCount;
            if (providerFieldList == null && _fieldList != null)
            {
                // First postback of the page.
                // Generate controls from _fieldList provided by 
                // consumer Web Part.
                string[] FieldList = _fieldList;
                fieldCount = FieldList.Length;
            
                _filterInputs = new TextBox[fieldCount];
                for (int index = 0; index < fieldCount; index++)
                {
                    _filterInputs[index] = new TextBox();
                    _filterInputs[index].ID = FieldList[index];
                    Controls.Add(_filterInputs[index]);

                    // Populate ViewState providerFieldList item to 
                    // keep track of field names.
                    if (index < fieldCount - 1)
                        ViewState[_fieldListKey] += 
                           FieldList[index].ToString() + ";";
                    else
                        ViewState[_fieldListKey] += 
                           FieldList[index].ToString();
                }
            }
            else if (providerFieldList != null)
            {
                // Subsequent postback of page. 
                // Retrieve the field names from StateBag 
                // providerFieldList
                // Need to parse the providerFieldList information to 
                // get the individual fields
                string[] FieldList = providerFieldList.Split(new Char[] 
                   {';'});
                fieldCount = FieldList.Length;

                _filterInputs = new TextBox[fieldCount];
                for (int index = 0; index < fieldCount; index++)
                {
                    _filterInputs[index] = new TextBox();
                    _filterInputs[index].ID = FieldList[index];
                    Controls.Add(_filterInputs[index]);
                }
            }

            // Add event handler to listen for button's Click event.
            _setFilterClicked = false; // Initialize to false -- user 
               hasn't clicked yet
            _setFilterButton.Click += new 
               EventHandler(SetFilterButtonClicked); 
            // listen for Button's click event

            _clearFilterClicked = false; // Initialize to false -- user 
               hasn't clicked yet
            _clearFilterButton.Click += new 
               EventHandler(ClearFilterButtonClicked); 
           // listen for Button's click event
    
            _noFilterClicked = false; // Initialize to false -- user 
               hasn't clicked yet
            _noFilterButton.Click += new 
               EventHandler(NoFilterButtonClicked); 
            // listen for Button's click event
        }

        // The button OnClick event handler.
        // <param name="sender">The Button object</param>
        // <param name="e">The Event Arguments</param>
        private void SetFilterButtonClicked(object sender, EventArgs e)
        {
            _setFilterClicked = true; //user clicked button, set to 
               true
        }

        private void ClearFilterButtonClicked(object sender, EventArgs e)
        {
            _clearFilterClicked = true; //user clicked button, set to 
               true
        }
    
        private void NoFilterButtonClicked(object sender, EventArgs e)
        {
            _noFilterClicked = true; //user clicked button, set to true
        }
    }
}

See Also

Reference

IFilterProvider Members

Microsoft.SharePoint.WebPartPages.Communication Namespace