Recipe 11.5. Communicating Between Web Parts


Problem

You have a web part in your application that needs to notify another web part when changes are made by the user. For example, suppose you have one web part that reads data from a database and acts a filter for a second web part displaying the filtered data. When the user changes the filter settings in the first web part, you want the second web part to be notified accordingly so it can display the new data.

Solution

Create a provider web part control, a consumer web part control, an interface to use as the communication contract between the web parts, and a page that uses both web part controls. In the provider web part control, add a method that returns the interface and is marked as the connection provider. In the consumer web part control, add a method that is passed the interface and is marked as the connection consumer. In the page that uses the web part controls, add a WebPartConnection control to the <StaticConnections> element of the WebPartManager defining the connection between the web parts.

The application we have implemented to demonstrate the solution is shown in Examples 11-17, 11-18, 11-19, 11-20, 11-21, 11-22 through 11-23. Examples 11-17 (VB) and 11-18 (C#) show the interface used for messages between the provider and consumer web parts. Examples 11-19 (VB) and 11-20 (C#) show the provider web part. Examples 11-21 (VB) and 11-22 (C#) show the consumer web part. Example 11-23 shows the .aspx for a page that demonstrates communicating between web parts. No code-behind is shown for the demonstration page because no code is required. Figure 11-7 shows the result.

Figure 11-7. Output of page demonstrating the communication between web parts


Discussion

The web parts framework provides the ability to communicate between web parts. The communication approach is a bit different from the scheme used to communicate between user controls (see Recipe 5.4). Instead of broadcasting an event, which can be consumed by many user controls, web part communication is explicitly "wired" between two web parts. Web parts can participate in communication with multiple web parts but each communication path consists of a single provider web part and a single consumer web part.

The communication path can be static (defined declaratively in the page that uses the controls) or dynamic (created programmatically or by the user). This recipe describes creating a static connection between web parts. For more information on connections between web parts, refer to the documentation on the WebPartConnection class in the MSDN Library.

Establishing a static connection between web parts requires four steps:

  1. Define an interface that will be used as the communication contract between the web parts.

  2. Add a method to the provider web part that returns the interface and is decorated with the ConnectionProvider attribute.

  3. Add a method to the consumer web part that is passed the interface and is decorated with the ConnectionConsumer attribute.

  4. Add a WebPartConnection control in the <StaticConnections> element of the WebPartManager control in the page where the web parts are used specifying the ID of the provider web part and the ID of the consumer web part.

Once these four steps have been implemented, the web part infrastructure handles calling the provider to get the data and then calling the consumer to supply the data.

In our application that implements this solution, our provider web part contains a DropDownList control with the categories of books in a database. Our consumer web part displays a list of books for the selected category.

The interface we created as the communication contract defines a single property (BookCategory) that provides the ability to pass the selected book category from the provider web part to the consumer web part.

 

Option Explicit On Option Strict On Namespace ASPNetCookbook.VBExamples ''' <summary> ''' This interface provides the definition of the definition of the ''' properties shared between web parts ''' </summary> Public Interface IBookCategoryVB '''*********************************************************************** ''' <summary> ''' This property defines the category for the book data ''' </summary> Property BookCategory() As String End Interface End Namespace

using System; /// <summary> /// This interface provides the definition of the definition of the /// properties shared between web parts /// </summary> namespace ASPNetCookbook.CSExamples { public interface IBookCategoryCS { ///*********************************************************************** /// <summary> /// This property defines the category for the book data /// </summary> String BookCategory { get; set; } } // IBookCategoryCS }

The CreateChildControls method of the provider web part class creates a DropDownList and a SqlDataSource control to display the available book categories in the same manner as described in Recipe 11.3. In addition, the class has a constructor that disables the Close button in the web part title bar since we do not want the user to be able to close the web part in this example.

 

Me.AllowClose = False

this.AllowClose = false;

The provider web part also has a BookCategory property to get the currently selected category from the DropDownList and to select an entry in the DropDownList when the property is being set:

 

Public Property BookCategory( ) As String _ Implements IBookCategoryVB.BookCategory Get 'make sure the child controls have been created EnsureChildControls( ) Return (ddBookCategories.SelectedValue) End Get Set(ByVal value As String) 'make sure the child controls have been created EnsureChildControls( ) 'find the item matching the passed value in the drop down list 'and select it ddBookCategories.SelectedIndex = _ ddBookCategories.Items.IndexOf(ddBookCategories.Items.FindByValue(value)) End Set End Property

public String BookCategory { get { // make sure the child controls have been created EnsureChildControls( ); return (ddBookCategories.SelectedValue); } set { // make sure the child controls have been created EnsureChildControls( ); // find the item matching the passed value in the drop down list // and select it ddBookCategories.SelectedIndex = ddBookCategories.Items.IndexOf(ddBookCategories.Items.FindByValue(value)); } }

The setter and getters of the property make a call to the EnsureChildControls method of the web part. This method checks to see if the child controls have been created; if they have not, it will make the necessary calls to create the child controls. If the call to EnsureChildControls is not made, it will be possible for the property to be accessed before the child controls are created, resulting in an exception being thrown because the ddBookCategories control is null.


The GetConnectionInterface method of the provider web part is the method called by the web part infrastructure to get the book category data. The method returns a reference to the instance of the provider web part. It is decorated with the ConnectionProvider attribute to define the method used as the provider of the data in the communications.

 

<ConnectionProvider("BookCategory")> _ Public Function GetConnectionInterface( ) As IBookCategoryVB Return Me End Function 'GetConnectionInterface

[ConnectionProvider("BookCategory")] public IBookCategoryCS GetConnectionInterface( ) { return (this); } // GetConnectionInterface

The consumer web part in our example is a modification of the book list web part created in Recipe 11.3. We have added a constructor to disable the Close button in the web part title bar in the same manner as we did for the provider web part.

We have added a BookCategory property and a SetConnectionInterface method. The BookCategory property provides the ability to get and set the book category used to filter the list of books retrieved from a database.

The SetConnectionInterface method of the consumer web part is called by the web part infrastructure to pass the book category data read from the provider web part. It is decorated with the ConnectionConsumer attribute to define the method used as the consumer of the data in the communications.

The SetConnectionInterface method sets the BookCategory property, filters the data in the data source to include only the books in the selected category, and sets the title of the web part to include the book category:

 

<ConnectionConsumer("BookCategory")> _ Public Sub SetConnectionInterface(ByVal bookCategoryInterface As IBookCategoryVB) 'make the child controls have been created EnsureChildControls( ) 'set the book category to the selected category BookCategory = bookCategoryInterface.BookCategory

'filter the data source for the selected category dSource.FilterExpression = "Category='" &BookCategory &"'" 'set the title of the web part to include the selected category MyBase.Title = "Book Data For " &BookCategory &" Category"
End Sub 'SetConnectionInterface

[ConnectionConsumer("BookCategory")] public void SetConnectionInterface(IBookCategoryCS bookCategoryInterface) { // make the child controls have been created EnsureChildControls( ); // set the book category to the selected category BookCategory = bookCategoryInterface.BookCategory; // filter the data source for the selected category dSource.FilterExpression = "Category='" + BookCategory + "'"; // set the title of the web part to include the selected category base.Title = "Book Data For " + BookCategory + " Category"; } // SetConnectionInterface

The final step to making it all work is to define the connection between the provider and consumer web parts. We do this by adding WebPartConnection control to the <StaticConnections> element of the WebPartManager in the demonstration page, setting the ProviderID attribute to the ID of the provider web part and the ConsumerID attribute to the ID of the consumer web part.

 <asp:WebPartManager  runat="server" > <StaticConnections> <asp:WebPartConnection    Consumer   Provider /> </StaticConnections> </asp:WebPartManager> 

Adding communications between web parts improves their reusability. By creating task-focused web parts, such as providing the ability for the user to select a book category in one web part and displaying the data in another web part, the controls can be reused for different tasks in other pages and applications.

Web part communication is not limited to custom web parts. Custom server controls and user controls can use the same techniques described in this recipe to participate in communications between web parts.


See Also

Recipe 5.4 and 11.3

Example 11-17. Interface class used as the message between web parts (.vb)

 Option Explicit On Option Strict On Namespace ASPNetCookbook.VBExamples ''' <summary> ''' This interface provides the definition of the definition of the ''' properties shared between web parts ''' </summary> Public Interface IBookCategoryVB '''*********************************************************************** ''' <summary> ''' This property defines the category for the book data ''' </summary> Property BookCategory( ) As String End Interface End Namespace 

Example 11-18. Interface class used as the message between web parts (.cs)

 using System; /// <summary> /// This interface provides the definition of the definition of the /// properties shared between web parts /// </summary> namespace ASPNetCookbook.CSExamples { public interface IBookCategoryCS { ///*********************************************************************** /// <summary> /// This property defines the category for the book data /// </summary> String BookCategory { get; set; } } // IBookCategoryCS } 

Example 11-19. Communicating between web partsprovider web part control (.vb)

 Option Explicit On Option Strict On Imports System.Configuration Imports System.Data Imports System.Data.SqlClient Namespace ASPNetCookbook.VBExamples ''' <summary> ''' This class provides a custom web part that displays the available ''' book categories and provides the ability to notify other web parts ''' when the user selects a new category ''' </summary> Public Class CH11BookCategoryWebPartVB Inherits WebPart Implements IBookCategoryVB Private ddBookCategories As DropDownList '''*********************************************************************** ''' <summary> ''' This property provides the ability to get the selected book category ''' </summary> Public Property BookCategory( ) As String _ Implements IBookCategoryVB.BookCategory Get 'make sure the child controls have been created EnsureChildControls( ) Return (ddBookCategories.SelectedValue) End Get Set(ByVal value As String) 'make sure the child controls have been created EnsureChildControls( ) 'find the item matching the passed value in the drop down list 'and select it ddBookCategories.SelectedIndex = _ ddBookCategories.Items.IndexOf(ddBookCategories.Items.FindByValue(value)) End Set End Property '''*********************************************************************** ''' <summary> ''' This routine provides the interface for obtaining the selected ''' category when the data has changed ''' </summary> <ConnectionProvider("BookCategory")> _ Public Function GetConnectionInterface( ) As IBookCategoryVB Return Me End Function 'GetConnectionInterface '''*********************************************************************** ''' <summary> ''' This constructor initializes the web part to default values ''' </summary> ''' <remarks></remarks> Public Sub New( ) 'disable the "close" verb Me.AllowClose = False End Sub 'New '''*********************************************************************** ''' <summary> ''' This routine creates the child controls (book category DropDownList) ''' for the web part ''' </summary> Protected Overrides Sub CreateChildControls( ) Dim dSource As SqlDataSource 'clear the controls collection Controls.Clear( ) 'create the dropdown list and add it to the custom web part controls ddBookCategories = New DropDownList( ) ddBookCategories.AutoPostBack = True Me.Controls.Add(ddBookCategories) 'create a SQL data source and set its properties to get the book 'categories from a database dSource = New SqlDataSource( ) dSource.ConnectionString = ConfigurationManager. _ ConnectionStrings("dbConnectionString").ConnectionString dSource.DataSourceMode = SqlDataSourceMode.DataSet dSource.ProviderName = "System.Data.OleDb" dSource.SelectCommand = "SELECT DISTINCT Category " &_ "FROM Book " &_ "ORDER BY Category ASC" 'set the data source for the DropDownList and bind the data ddBookCategories.DataSource = dSource ddBookCategories.DataTextField = "Category" ddBookCategories.DataBind( ) 'add the SQL data source to the custom web part controls Me.Controls.Add(dSource) End Sub 'CreateChildControls End Class 'CH11BookCategoryWebPartVB End Namespace 

Example 11-20. Communicating between web partsprovider web part control (.cs)

 using System; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; namespace ASPNetCookbook.CSExamples { /// <summary> /// This class provides a custom web part that displays book data /// </summary> public class CH11BookCategoryWebPartCS : WebPart, IBookCategoryCS { private DropDownList ddBookCategories = null; ///*********************************************************************** /// <summary> /// This property provides the ability to get the selected book category /// </summary> public String BookCategory { get { // make sure the child controls have been created EnsureChildControls( ); return (ddBookCategories.SelectedValue); } set { // make sure the child controls have been created EnsureChildControls( ); // find the item matching the passed value in the drop down list // and select it ddBookCategories.SelectedIndex = ddBookCategories.Items.IndexOf(ddBookCategories.Items.FindByValue(value)); } } ///*********************************************************************** /// <summary> /// This routine provides the interface for obtaining the selected /// category when the data has changed /// </summary> [ConnectionProvider("BookCategory")] public IBookCategoryCS GetConnectionInterface( ) { return (this); } // GetConnectionInterface ///*********************************************************************** /// <summary> /// This constructor initializes the web part to default values /// </summary> /// <remarks></remarks> public CH11BookCategoryWebPartCS( ) { // disable the "close" verb this.AllowClose = false; } // CH11BookCategoryWebPartCS ///*********************************************************************** /// <summary> /// This routine creates the child controls (book category DropDownList) /// for the web part /// </summary> protected override void CreateChildControls( ) { SqlDataSource dSource; // clear the controls collection Controls.Clear( ); // create the dropdown list and add it to the custom web part controls ddBookCategories = new DropDownList( ); ddBookCategories.AutoPostBack = true; this.Controls.Add(ddBookCategories); // create a SQL data source and set its properties to get the book // categories from a database dSource = new SqlDataSource( ); dSource.ConnectionString = ConfigurationManager. ConnectionStrings["dbConnectionString"].ConnectionString; dSource.DataSourceMode = SqlDataSourceMode.DataSet; dSource.ProviderName = "System.Data.OleDb"; dSource.SelectCommand = "SELECT DISTINCT Category " + "FROM Book " + "ORDER BY Category ASC"; // set the data source for the DropDownList and bind the data ddBookCategories.DataSource = dSource; ddBookCategories.DataTextField = "Category"; ddBookCategories.DataBind( ); // add the SQL data source to the custom web part controls this.Controls.Add(dSource); } // CreateChildControls } // CH11BookCategoryWebPartCS } 

Example 11-21. Communicating between web partsconsumer web part control (.vb)

 Option Explicit On Option Strict On Imports System.Configuration Imports System.Data Imports System.Data.SqlClient Namespace ASPNetCookbook.VBExamples ''' <summary> ''' This class provides a custom web part that displays book data ''' and provides the ability to be notified by another web part ''' that the selected book category has changed ''' </summary> Public Class CH11CustomWebPartWithCommVB Inherits WebPart Private gvData As GridView Private dSource As SqlDataSource Private mBookCategory As String '''*********************************************************************** ''' <summary> ''' This property provides the ability to get/set the BookCategory ''' </summary> Public Property BookCategory( ) As String Get Return (mBookCategory) End Get Set(ByVal value As String) mBookCategory = value End Set End Property '''*********************************************************************** ''' <summary> ''' This routine provides the interface that is called to be notified ''' that the selected category has been changed ''' </summary> ''' ''' <param name="bookCategoryInterface">Set to book category data</param> <ConnectionConsumer("BookCategory")> _ Public Sub SetConnectionInterface( _ ByVal bookCategoryInterface As IBookCategoryVB) 'make the child controls have been created EnsureChildControls( ) 'set the book category to the selected category BookCategory = bookCategoryInterface.BookCategory 'filter the data source for the selected category dSource.FilterExpression = "Category='" &BookCategory &"'" 'set the title of the web part to include the selected category MyBase.Title = "Book Data For " &BookCategory &" Category" End Sub 'SetConnectionInterface '''*********************************************************************** ''' <summary> ''' This constructor initializes the web part to default values ''' </summary> Public Sub New( ) 'set the default title MyBase.Title = "Book Data For All Categories" 'disable the "close" verb Me.AllowClose = False End Sub 'New '''*********************************************************************** ''' <summary> ''' This routine creates the child controls (GridView and SqlDataSource) ''' for the web part ''' </summary> Protected Overrides Sub CreateChildControls( ) Dim gridColumn As BoundField 'clear the controls collection Controls.Clear( ) 'create the GridView control and set the applicable properties 'to display the book data gvData = New GridView( ) gvData.AllowPaging = True gvData.AllowSorting = True gvData.AutoGenerateColumns = False gvData.BorderColor = Drawing.ColorTranslator.FromHtml("#000080") gvData.BorderStyle = WebControls.BorderStyle.Solid gvData.BorderWidth = 2 gvData.Caption = "" gvData.HorizontalAlign = WebControls.HorizontalAlign.Center gvData.Width = 600 gvData.PageSize = 5 gvData.PagerSettings.Mode = PagerButtons.Numeric gvData.PagerSettings.PageButtonCount = 5 gvData.PagerSettings.Position = PagerPosition.Bottom gvData.PagerStyle.HorizontalAlign = WebControls.HorizontalAlign.Center gvData.PagerStyle.CssClass = "pagerText" gvData.HeaderStyle.HorizontalAlign = WebControls.HorizontalAlign.Center gvData.HeaderStyle.CssClass = "tableHeader" gvData.RowStyle.CssClass = "tableCellNormal" gvData.AlternatingRowStyle.CssClass = "tableCellAlternating" 'create the columns in the GridView gridColumn = New BoundField( ) gridColumn.DataField = "Title" gridColumn.HeaderText = "Title" gridColumn.SortExpression = "Title" gvData.Columns.Add(gridColumn) gridColumn = New BoundField( ) gridColumn.DataField = "PublishDate" gridColumn.HeaderText = "Publish Date" gridColumn.SortExpression = "PublishDate" gridColumn.DataFormatString = "{0:MMM dd, yyyy}" gridColumn.ItemStyle.HorizontalAlign = WebControls.HorizontalAlign.Center gvData.Columns.Add(gridColumn) gridColumn = New BoundField( ) gridColumn.DataField = "ListPrice" gridColumn.HeaderText = "List Price" gridColumn.SortExpression = "ListPrice" gridColumn.DataFormatString = "{0:C2}" gridColumn.ItemStyle.HorizontalAlign = WebControls.HorizontalAlign.Center gvData.Columns.Add(gridColumn) 'add the event handler for the GridView RowCreated event AddHandler gvData.RowCreated, AddressOf gvData_RowCreated 'add the GridView to the custom web part controls Me.Controls.Add(gvData) 'create a SQL data source and set its properties to get the book data 'from a database dSource = New SqlDataSource( ) dSource.ConnectionString = ConfigurationManager. _ ConnectionStrings("dbConnectionString").ConnectionString dSource.DataSourceMode = SqlDataSourceMode.DataSet dSource.ProviderName = "System.Data.OleDb" dSource.ID = "dSource" dSource.SelectCommand = "SELECT Title, PublishDate, ListPrice, Category " &_ "FROM Book " &_ "ORDER BY Title" 'set the data source ID for the GridView 'NOTE: The DataSourceID must be used instead of the DataSource if the '    automatic sorting/paging in GridView are to be used. gvData.DataSourceID = dSource.ID 'add the SQL data source to the custom web part controls Me.Controls.Add(dSource) 'perform the initial sort on the first column in ascending order 'if no sort expression is currently set (this is the case when the 'control is initially created) If (gvData.SortExpression.Length = 0) Then gvData.Sort(gvData.Columns(0).SortExpression, _ SortDirection.Ascending) End If End Sub 'CreateChildControls '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the GridView's row created ''' event. It is responsible for setting the icon in the header row to ''' indicate the current sort column and sort order ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Protected Sub gvData_RowCreated(ByVal sender As Object, _ ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Dim index As Integer Dim col As DataControlField = Nothing Dim image As HtmlImage = Nothing If (e.Row.RowType = DataControlRowType.Header) Then 'loop through the columns in the gridview updating the header to 'mark which column is the sort column and the sort order For index = 0 To gvData.Columns.Count - 1 col = gvData.Columns(index) 'check to see if this is the sort column If (col.SortExpression.Equals(gvData.SortExpression)) Then 'this is the sort column so determine whether the ascending or 'descending image needs to be included image = New HtmlImage( ) image.Border = 0 If (gvData.SortDirection = SortDirection.Ascending) Then image.Src = "images/sort_ascending.gif" Else image.Src = "images/sort_descending.gif" End If 'add the image to the column header e.Row.Cells(index).Controls.Add(image) End If 'If (col.SortExpression = sortExpression) Next index End If 'If (gvData.SortExpression.Equals(String.Empty)) End Sub End Class 'CH11CustomWebPartWithCommVB End Namespace 

Example 11-22. Communicating between web partsconsumer web part control (.cs)

 using System; using System.Drawing; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; namespace ASPNetCookbook.CSExamples { /// <summary>     /// This class provides a custom web part that displays book data /// and provides the ability to be notified by another web part /// that the selected book category has changed /// </summary> public class CH11CustomWebPartWithCommCS : WebPart { private GridView gvData = null; private SqlDataSource dSource = null; private String mBookCategory = null; ///*********************************************************************** /// <summary> /// This property provides the ability to get/set the BookCategory /// </summary> public String BookCategory { get { return (mBookCategory); } set { mBookCategory = value; } } ///*********************************************************************** /// <summary> /// This routine provides the interface that is called to be notified /// that the selected category has been changed /// </summary> /// /// <param name="bookCategoryInterface">Set to book category data</param> [ConnectionConsumer("BookCategory")] public void SetConnectionInterface(IBookCategoryCS bookCategoryInterface) { // make the child controls have been created EnsureChildControls( ); // set the book category to the selected category BookCategory = bookCategoryInterface.BookCategory; // filter the data source for the selected category dSource.FilterExpression = "Category='" + BookCategory + "'"; // set the title of the web part to include the selected category base.Title = "Book Data For " + BookCategory + " Category"; } // SetConnectionInterface ///*********************************************************************** /// <summary> /// This constructor initializes the web part to default values /// </summary> /// <remarks></remarks> public CH11CustomWebPartWithCommCS( ) { /// set the default title base.Title = "Book Data For All Categories"; // disable the "close" verb this.AllowClose = false; } // CH11CustomWebPartWithCommCS ///*********************************************************************** /// <summary> /// This routine creates the child controls (GridView and SqlDataSource) /// for the web part /// </summary> protected override void CreateChildControls( ) { BoundField gridColumn; // clear the controls collection Controls.Clear( ); // create the GridView control and set the applicable properties // to display the book data gvData = new GridView( ); gvData.AllowPaging = true; gvData.AllowSorting = true; gvData.AutoGenerateColumns = false; gvData.BorderColor = ColorTranslator.FromHtml("#000080"); gvData.BorderStyle = BorderStyle.Solid; gvData.BorderWidth = 2; gvData.Caption = ""; gvData.HorizontalAlign = HorizontalAlign.Center; gvData.Width = 600; gvData.PageSize = 5; gvData.PagerSettings.Mode = PagerButtons.Numeric; gvData.PagerSettings.PageButtonCount = 5; gvData.PagerSettings.Position = PagerPosition.Bottom; gvData.PagerStyle.HorizontalAlign = HorizontalAlign.Center; gvData.PagerStyle.CssClass = "pagerText"; gvData.HeaderStyle.HorizontalAlign = HorizontalAlign.Center; gvData.HeaderStyle.CssClass = "tableHeader"; gvData.RowStyle.CssClass = "tableCellNormal"; gvData.AlternatingRowStyle.CssClass = "tableCellAlternating"; // create the columns in the GridView gridColumn = new BoundField( ); gridColumn.DataField = "Title"; gridColumn.HeaderText = "Title"; gridColumn.SortExpression = "Title"; gvData.Columns.Add(gridColumn); gridColumn = new BoundField( ); gridColumn.DataField = "PublishDate"; gridColumn.HeaderText = "Publish Date"; gridColumn.SortExpression = "PublishDate"; gridColumn.DataFormatString = "{0:MMM dd, yyyy}"; gridColumn.ItemStyle.HorizontalAlign = HorizontalAlign.Center; gvData.Columns.Add(gridColumn); gridColumn = new BoundField( ); gridColumn.DataField = "ListPrice"; gridColumn.HeaderText = "List Price"; gridColumn.SortExpression = "ListPrice"; gridColumn.DataFormatString = "{0:C2}"; gridColumn.ItemStyle.HorizontalAlign = HorizontalAlign.Center; gvData.Columns.Add(gridColumn); // add the event handler for the GridView RowCreated event gvData.RowCreated += new GridViewRowEventHandler(gvData_RowCreated); // add the GridView to the custom web part controls this.Controls.Add(gvData); // create a SQL data source and set its properties to get the book data // from a database dSource = new SqlDataSource( ); dSource.ConnectionString = ConfigurationManager. ConnectionStrings["dbConnectionString"].ConnectionString; dSource.DataSourceMode = SqlDataSourceMode.DataSet; dSource.ProviderName = "System.Data.OleDb"; dSource.ID = "dSource"; dSource.SelectCommand = "SELECT Title, PublishDate, ListPrice, Category " + "FROM Book " + "ORDER BY Title"; // set the data source ID for the GridView // NOTE: The DataSourceID must be used instead of the DataSource if the //  automatic sorting/paging in GridView are to be used. gvData.DataSourceID = dSource.ID; // add the SQL data source to the custom web part controls this.Controls.Add(dSource); // perform the initial sort on the first column in ascending order // if no sort expression is currently set (this is the case when the // control is initially created) if (gvData.SortExpression.Length == 0) { gvData.Sort(gvData.Columns[0].SortExpression, SortDirection.Ascending); } } // CreateChildControls ///*********************************************************************** /// <summary> /// This routine provides the event handler for the GridView's row created /// event. It is responsible for setting the icon in the header row to /// indicate the current sort column and sort order /// </summary> /// /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void gvData_RowCreated(Object sender, System.Web.UI.WebControls.GridViewRowEventArgs e) { DataControlField col = null; HtmlImage image = null; if (e.Row.RowType == DataControlRowType.Header) { // loop through the columns in the gridview updating the header to // mark which column is the sort column and the sort order for (int index = 0; index < gvData.Columns.Count; index++) { col = gvData.Columns[index]; // check to see if this is the sort column if (col.SortExpression.Equals(gvData.SortExpression)) { // this is the sort column so determine whether the ascending or // descending image needs to be included image = new HtmlImage( ); image.Border = 0; if (gvData.SortDirection == SortDirection.Ascending) { image.Src = "images/sort_ascending.gif"; } else { image.Src = "images/sort_descending.gif"; } // add the image to the column header e.Row.Cells[index].Controls.Add(image); } // if (col.SortExpression.Equals(gvBooks.SortExpression)) } // for index } // if (e.Row.RowType == DataControlRowType.Header) } //gvData_RowCreated } // CH11CustomWebPartWithCommCS } 

Example 11-23. Communicating between web partsdemonstration page (.aspx)

 <%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master" AutoEventWireup="false" CodeFile="CH11TestCommunicatingBetweenWebPartsVB.aspx.vb" Inherits="ASPNetCookbook.VBExamples.CH11TestCommunicatingBetweenWebPartsVB" Title="Communicating Between Web Parts" %> <%@ Register TagPrefix="ASPNetCookbook"  Namespace="ASPNetCookbook.VBExamples"  Assembly="_ _Code" %> <asp:Content  runat="server" ContentPlaceHolder> <div align="center" > Communicating Between Web Parts (VB) </div> <asp:WebPartManager  runat="server" > <StaticConnections> <asp:WebPartConnection     Consumer    Provider /> </StaticConnections> </asp:WebPartManager> <table width="90%" align="center" border="1" cellpadding="4" cellspacing="0"> <tr> <td> <asp:WebPartZone  runat="server" Css> <ZoneTemplate> <ASPNetCookbook:CH11BookCategoryWebPartVB  runat="server" Title="Book Categories" /> </ZoneTemplate> </asp:WebPartZone> </td> </tr> <tr> <td> <asp:WebPartZone  runat="server" Css> <ZoneTemplate> <ASPNetCookbook:CH11CustomWebPartWithCommVB  runat="server" Title="Book Data" /> </ZoneTemplate> </asp:WebPartZone> </td> </tr> </table> </asp:Content> 



ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2003
Pages: 202

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net