Tuesday 26 February 2008

Webparts in MOSS 2007 - Part 4

The examples we have seen until now talks about webparts that worked independently (and good :)). Assuming we need to get two webparts to talk with each other, you need to follow this :

1.) Setup a data object interface which would be shared by the two webparts.
public interface ISharedData
{
string data { get; set; }
}

2.) On the source/provider webpart, perform the following actions :

a.) Implement our data object interface. The below sample returns the value from a text field.
string ISharedData.data
{
get { return txtData.Text; }
set { txtData.Text = value; }
}


b.) Setup a connection point which the consumer object can use. For this, use the ConnectionProvider attribute.
[ConnectionProvider("Sample Shared Data Provider")]
public ISharedData GetCommunicationPoint()
{
return this as ISharedData;
}

3.) On the consumer webpart , access the connection point (and effectively the shared data) by implementing a method which is marked with the ConnectionConsumer attribute.
[ConnectionConsumer("Shared Data Consumer")]
public void InitializeProvider(ISharedData provider)
{
SharedData = provider;
}


Note that the argument of this custom method is set to the shared interface. When MOSS calls this routine (since we have used the ConnectionConsumer attribute), the parameter provider would be set to the source webpart's interface. Save this value in a local variable for later usage.

Do note that the value maintained in the above private variable was available for usage ONLY the PreRender function of the WebPart. Is it because I have not saved it in a session object ?

protected override void OnPreRender(EventArgs e)
{
if (_sharedData != null)
{
/*use the shared data*/
lblData.Text = "Data from other web part = " + _sharedData.data;
}
}

Anyways, the above bits should get you started with inter webpart communication. Once you have deployed the above two webparts, use the design mode of the zone to setup the source and destination connections.

Note that for intra-webzone webpart communication, things appear to get a bit different. I havent tried it, but you would need to start with changing the parent class for the WebPart (mentioned in Part 1) .

No comments: