Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Diagram
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » How do I » WebParts Communication: How WebParts on a page communicate with each other

WebParts Communication: How WebParts on a page communicate with each other


In this tutorial we will describe how to make WebParts on a WebParts Page communicate with each other. So will see how to use ConnectionsZone and how to enable WebParts to talk to each other by connecting them.

Author Rank:
Total page views :  57270
Total downloads :  1287
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
WebPartsArticlePartIII.zip
 
Become a Sponsor


Introduction:

In this tutorial we will describe how to make WebParts on a WebParts Page communicate with each other. So will see how to use ConnectionsZone and how to enable WebParts to talk to each other by connecting them.

Assumptions:

This tutorial assumes that you know how to work with web forms, creating user controls and connecting to data sources using SqlDataSource Control. Also you should know how to use WebPartZone control and to know what are WebParts and WebParts Pages.

How to implement connections between 2 WebParts:

The scenario is, we have 2 web parts, one display a drop down list of publishers, and the other display grid view of titles related to a specific publisher. So whenever I change the selection from the drop down list, the grid view should repopulated with the titles related to the selected publisher. This is very simple scenario just to show you how to implement WebParts Connections.

Preparing the WebParts Page:

  1. Create new WebForm, Name it WebPartsConnections.aspx, Also create 2 user controls, name them as UCPublishers.ascx & UCTitles.ascx.
  2. Open UCPublishers.ascx, drag and drop SqlDataSource control -name it sdsPubs- into it as well as a DropDownList -name it cmbPubs- and set its AutoPostBack Property to ture.
  3. Configure the SqlDataSource to select [pub_id] and [pub_name] from publishers table in pubs Database sample.

    UCPublishersCode.JPG
  4. Open UCTitles.ascx, drage and drop SqlDataSource control -name it sdsTitles- into it as well as a GridView -name it dvTitles-. Also drag and drop a HiddenField Control -name it hfSelectedPublisherID-
  5. Configure you SqlDataSource to select [title], [price] and [pubdate] from [titles] table in Pubs sample database, with pub_id as parameter. Configure the parameter to be a control parameter, and its value populated tom the HiddenField Control.

     UCTitlesCode.JPG
  6. Now Open your WebPartsConnections.aspx, Insert table with one column and one row.
  7. Drag and drop WebPartManager Control into the page-name it wpManager-
  8. Drag and drop 2 WebPartZone controls into the table, name them as wpzTop & wpzBottom.
  9. Drag and drop the UCPublishers.ascx from the solution explorer into the wpzTop. Do the same for UCTitles.ascx but drop it into wpzBottom. You can configure the Zones to use AutoFormat Professional Style.

  10. You can now Test the page. Notice that there is nothing happens when you change the publisher.

Building the Connection:

To implement the connection functionality between WebParts, we should create an Interface. This interface would be implemented by both UCPublishers.ascx as Connection Provider, and UCTitles.ascx as Connection Consumer. This interface serves as a contract for the communication between the provider and consumer.
We will name our Interface as ISelectedPublisher:

  1. Right click on App_Code and select New Item. (Create ISelectedPublisher.cs)

    public interface ISelectedPublisher
    {
    //ID of the selected publisher
    string
    SeletedPublisherID{get;}
    }

  2. Now open your UCPublishers.ascx in Code-View and implement the ISelectedPublisher as the following

    public partial class UCPublishers : System.Web.UI.UserControl, ISelectedPublisher
    {

    #region ISelectedPublisher Members

    //Get the Selected Value from the DropDownList that holds Publishers
    public string
    SeletedPublisherID
    {

    get { return cmbPubs.SelectedValue; }

    }

    #endregion

    [ConnectionProvider("SelectedPublisher", "SelectedPublisher")]
    public ISelectedPublisher GetSelectedPublisher()
    {

    return this;

    }
    }

    Essentially, we are implementing the ISelectedPublisher interface and creating a provider connection point by using the ConnectionProvider attribute. So we implemented the SelectedPublisherID property to return the selected publisher id from the DropDownList.

    Also we created the GetSelectedPublisher method. It is marked as ConnectionProvider, The first parameter to the ConnectionProvider attribute assigns a friendly name to the provider connection point. The second parameter assigns a unique ID to the provider connection point. Note the returned object is "this", which mean to consider the control instance itself as the connection provider.

  3. It is time to implement the Consumer now, so open the Code-View of your UCTitles.ascx and Consume the connection provided by the Provider:

    public partial class UCTitles : System.Web.UI.UserControl
    {

    private ISelectedPublisher _publisher = null;

    [ConnectionConsumer("SelectedPublisher", "SelectedPublisher")]
    public void SetSelectedPublisher(ISelectedPublisher selectedPublisher)
    {

    _publisher = selectedPublisher;

    }
    protected override void OnPreRender(EventArgs e)
    {

    base.OnPreRender(e);
    if (_publisher != null)
    {

    hfSelectedPublisherID.Value = _publisher.SeletedPublisherID;

    }

    }

    }

    Essentially, we are using the ConnectionConsumer attribute to define a consumer connection point -The SetSelectedPublisher Method-, and allowing it to act as a receiver of the ISelectedPublisher interface. The publisher that is received is then appended to the hidden field in the UCTitles.ascx Control on the PreRender event. The first parameter to the ConnectionConsumer attribute assigns a friendly name to the consumer connection point. The second parameter assigns a unique ID to the consumer connection point.
  4. Now Select the WebPartManager Control in your page -wpManager-
  5. From the property window, select ellipses beside the StaticConnections property. Configure it as the following.

    WebPartManagerConfig.JPG

    The ConsumerID is the ID of the Consumer Control, in our case it is the UCTitles Control which has the default ID UCTitles1.

    The ProviderID is the ID of the Provider Control, in out case it is the UCPublishers Control which has the dfault ID UCPublishers1.

    ConsumerConnectionPointID and ProviderConnectionPointID are the Attributes parameters mentioned earlier.

     WebPartManagerCode.JPG
  6. Now its time to test your Page. Run it and change the publisher, you will notice that the Titles is changed in the GridView to display the publisher's Titles.

Working with ConnectionsZone:

Now we will Connect and Disconnect the WebParts Connections on the fly during runtime. To do so we need to use ConnectionsZone.

  1. Drag and drop ConnectionsZone Control into your page any place
  2. Add LinkButton to you page, -name it btnEditConnection- and set the text to "Edit Connection".
  3. Double click on it to implement its click event handler.

    protected void btnEditConnection_Click(object sender, EventArgs e)
    {

    if (btnEditConnection.Text == "Edit Connection")
    {

    wpManager.DisplayMode = WebPartManager.ConnectDisplayMode;
    btnEditConnection.Text = "View Page";

    }
    else
    {

    wpManager.DisplayMode = WebPartManager.BrowseDisplayMode;
    btnEditConnection.Text = "Edit Connection";

    }

    }
  4. Again run your page and click on the button. From the any of the WebParts Menu on the top right corner of the WebPart select Connect. Note that the Connection Zone Appears now. Test your page to see what you can do on the fly with Connection Zone and WebParts

    ConnectionInAction.JPG

    ConnectionZone.JPG
     

Now we almost cover most of the basic features of WebParts and WebParts Pages. Hope this WebPart Tutorial series enrich your knowledge about WebParts and WebParts framework in ASP.Net 2. 

References:

For more information refer to the following references:


Login to add your contents and source code to this article
 About the author
 
Muhammad Mosa
Muhammad M. Mosa Soliman: Software Engineer, graduated from the Faculty of Computers & Information Systems year 2003-Ain Shams University- in Cairo. Working with Microsoft .NET technology since early beta releases. Main experiance based on ASP.NET, SharePoint Portal 2003 & SQL Server. Worked as trainer for Microsoft .NET for 2 years in Cairo. Likes to read about new technologies and self-learning. Extremly Hard worker when motivated. MCT MCSD.NET MCTS: .Net 2.0 Web/Windows Applications MCPD: Enterprise Application Developer MCTS: WSS 3.0 & MOSS 2007 Config
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Become a Sponsor
 Comments
Very good by Henrry On April 12, 2006

Thanks for taking time to build this example. But i have a question if you can answer me. When te page is open there is an item select in the dropdown list but no itens in the grid, and the 1º time (it happends only the 1º time) that i select an item in the dropdown the grid isn't populated. why?

Reply | Email | Delete | Modify | 
Re: Very good by Muhammad On April 13, 2006

Sorry for being late,

may be it is bug that I didn't notic, I'll check it back and I'll get back to you.

But this may take time. as I'm planning for my wedding :0)...

sorry for this bug,

Regards

Reply | Email | Delete | Modify | 
Re: Very good by Marc On April 25, 2007
I had the same experience because I didn't set the DataSource on the GridView "dvTitles".  Try adding DataSourceID="sdsTitles" in the UCTitles.ascx file to the "dvTitles" GridView.
Reply | Email | Delete | Modify | 
Can i use this webpart in sharepoint portal server by Ravi On April 20, 2006

WebParts Communication: How WebParts on a page communicate with each other

 

I am working  for my MS project

i want to display the data from the database table and

list view and when u click detail view and after that i need to update in the database

for this which the best way to do

if i create the webpart in the above sample way, how can i get the ".dwp" to import into share point server

 

Thank you very much for your help and samples in this site

Ravi

 

 

 

 

Reply | Email | Delete | Modify | 
Re: Can i use this webpart in sharepoint portal server by Muhammad On April 27, 2006

No you cannot use it with the current version of SPS.

I hope I could help you much in this.

Reply | Email | Delete | Modify | 
Dynamic web part connections? by Paul On June 2, 2006

Great article! I'm trying to implement dynamic web part connections. Does anyone know where I can get a tutorial? I would like to be able to add a control via the catalog and have it dynamically bind to a provider. Anyone know how? Thanks

 

paul

Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.8.14
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.