Web Part Connections in WSS 3.0 (Part 2)

In part 1 of this series, I showed how to make one web part accept data from another.  In this part, I'll show how one web part can send data to two different web parts. 

Let's add another web part.  We already have a web part that allows the user to select the number of disks to use in our Towers of Hanoi puzzle.  We also have a web part that displays the steps needed to solve the puzzle for that number of disks.  Now, let's add a web part that displays the number of steps the are needed.  This part will get it's data from the HanoiDisks web part, just like the HanoiSteps web part does.

HanoiCount.vb 

Imports System
Imports System.Drawing
Imports System.ComponentModel
Imports System.Web.UI.HtmlControls
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts

Public Class HanoiCount
Inherits WebPart

    Protected _diskInterface As IDisks = Nothing
Protected _disks As Integer = 0

    Protected _headerMessage As Literal = Nothing

    Protected Overrides Sub CreateChildControls()
MyBase.CreateChildControls()

        Try
_headerMessage = New Literal
Me.Controls.Add(_headerMessage)
Catch ex As Exception
Me.Controls.Clear()

            Dim msg As New Literal()
msg.Text = ex.Message
Me.Controls.Add(msg)
End Try

    End Sub

    Protected Overrides Sub OnPreRender(ByVal e As System.EventArgs)
MyBase.OnPreRender(e)

        If _diskInterface IsNot Nothing Then
_disks = _diskInterface.NumberOfDisks
End If

    End Sub

    Protected Overrides Sub RenderContents(ByVal writer As System.Web.UI.HtmlTextWriter)

        If _headerMessage IsNot Nothing AndAlso _disks > 1 Then
Dim steps As Integer = 2 ^ _disks - 1
With _headerMessage
.Text = "There are " & steps & " steps for " & _disks & " disks."
End With
End If

        MyBase.RenderContents(writer)

    End Sub

    <ConnectionConsumer("Number of Disks")> _
Public Sub AcceptDiskInterface(ByVal diskInterface As IDisks)
_diskInterface = diskInterface
End Sub

End Class

If you read part 1, then this should look very familiar.  In fact, there is no real difference between a web part providing data to one web part, and a web part providing data to many web parts.  Add this web part to the same page as the HanoiDisks and HanoiSteps web parts from part 1, and you see what I mean.

In my next post, I'll show you how to do something that IS a bit different.  I'll show you how one web part can accept data from two different web parts.