Pass Value From One Webpart to Another in in SharePoint 2010

Overview

Sometimes we need to pass data from one webpart to another webpart present in the same page in the site. We can do this by either OOB or by custom development. Custom development is one of the common ways to create a connected webpart. We need To create an Interface to implement the connection functionality between two WebParts, say Provider and Consumer.

The following is the step-by-step explanation to create a connected webpart in SharePoint 2010 to filter the value of the consumer webpart on the basis of the provider webpart.

Step1 : Create two lists (say Region and Country as provider and consumer, respectively).

In the Region List add Regions of the world as in the following:



In the Country List add Region as lookup and add countries corresponding to Regions.



Step 2 : Open Visual Studio and create a project by selecting empty SharePoint project from SharePoint 2010. Mark properly Trust Level and the the site where you want to deploy.

Step 3 : Add an Interface (say IConnectableNavigation).

Step 4 : Add the following block of code to the Interface:

public
 interface IConnectableNavigation
{
   string GetRegion { get; }

}

Step 5 : Add a Visual Webpart and name it as RegionsVWP.

Step 6 : Modify the code of RegionsVWP.cs as below.

public class RegionsVWP : WebPart,IConnectableNavigation
{
   Control control;
   // Visual Studio might automatically update this path when you change the Visual Web Part project item.
   private const string _ascxPath = @"~/_CONTROLTEMPLATES/SP.Labs.ConnectedWP/RegionsVWP/RegionsVWPUserControl.ascx";
   protected override void CreateChildControls()
   {
      control = Page.LoadControl(_ascxPath);
      Controls.Add(control);
   }
   protected override void OnInit(EventArgs e)
   {
      EnsureChildControls();
      base.OnInit(e);
   }
   public string GetRegion
   {
      get
      {
         return ((RegionsVWPUserControl)control).GetRegion();
      }
   }
   [ConnectionProvider("Rgions- Provider")]
   public IConnectableNavigation GetProvider()
   {
      return this;
   }
}

Step 7 : Open RegionsVWPUserControl.ascx and design the form as below

<table width="50%" style="background-color#FF9999">

    <tr>

        <td>

            <h1>

                Provider WebPart</h1>

        </td>

    </tr>

</table>

<br />

<br />

<table>

    <tr>

        <td>

            Regions

        </td>

        <td>

            <asp:DropDownList ID="ddlRegion" runat="server" AutoPostBack="true">

            </asp:DropDownList>

        </td>

    </tr>

</table>


Step 8 : Open RegionsVWPUserControl.ascx.cs and code as below.

protected void Page_Load(object sender, EventArgs e)
{
   if (!Page.IsPostBack)
   {
      BindRegions();
   }
}
private void BindRegions()
{
   string siteUrl = SPContext.Current.Site.Url;
   using (SPSite spSite = new SPSite(siteUrl))
   {
      using (SPWeb spWeb = spSite.OpenWeb())
      {
         SPList list = spWeb.Lists["Region"];

         DataTable dt = list.Items.GetDataTable();
         ddlRegion.DataSource = dt;
         ddlRegion.DataTextField = "Title";
         ddlRegion.DataValueField = "Id";ddlRegion.DataBind();
         ddlRegion.Items.Insert(0, new ListItem("--Select--", "0"));
         //DropDownList.SelectedIndex = 0;
      }
   }
}
public string GetRegion()
{
   if (ddlRegion.SelectedIndex > 0)
   {
      return ddlRegion.SelectedItem.Text;
   }
   else
   return string.Empty;
}

Step 9 : Add another Visual Webpart (say countryVWP) as consumer.

Step 10 : Modify the code of the CountryVWP class file as below.

public class CountryVWP : WebPart
{
   Control control;
   public IConnectableNavigation provider;
   // Visual Studio might automatically update this path when you change the Visual Web Part project item.
   private const string _ascxPath = @"~/_CONTROLTEMPLATES/SP.Labs.ConnectedWP/CountryVWP/CountryVWPUserControl.ascx";
   protected override void CreateChildControls()
   {
      control = Page.LoadControl(_ascxPath);
      Controls.Add(control);
   }
   protected override void OnInit(EventArgs e)
   {
      EnsureChildControls();
      base.OnInit(e);
   }
   [ConnectionConsumer("Country- Consumer")]
   public void CategoryConsumer(IConnectableNavigation p)
   {
      provider = p;
   }
   protected override void OnPreRender(EventArgs e)
   {
      base.OnPreRender(e);
      if (provider != null)
      {
         //if (!string.IsNullOrEmpty(provider.GetCategoryType))
         //{
         ((CountryVWPUserControl)control).BindCountry(provider.GetRegion);
         //}
      }
   }
}

Step 11 : Open CountryVWPUserControl.ascx and design it as below.

<table width="50%" style="background-color#FF9999">

    <tr>

        <td>

            <h1>

                Consumer WebPart</h1>

        </td>

    </tr>

</table>

<br />

<br />

<asp:GridView ID="grdCountry" runat="server" AutoGenerateColumns="false" 

    EmptyDataText="No record found, Please select Category." BackColor="#00CCFF" 

    Width="50%">

    <AlternatingRowStyle BackColor="#CCFF33" />

    <Columns>

        <asp:BoundField DataField="Title" HeaderText="Title" ReadOnly="True" />

    </Columns>

    <EmptyDataRowStyle BackColor="#CC0000" />

</asp:GridView>


Step 12 : Open the codefile CountryVWPUserControl.ascx.cs and write the code as below. This is the consumer webpart that displays the records depending on the parameter passed by the Provider webpart.

public CountryVWP cvwp { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
}
internal void BindCountry(string regions)
{
   string siteUrl = SPContext.Current.Site.Url;
   using (SPSite spSite = new SPSite(siteUrl))
   {
   using (SPWeb spWeb = spSite.OpenWeb())
   {
      SPList list = spWeb.Lists["Country"];
      SPQuery query = new SPQuery();
      query.Query = "<Where><Eq><FieldRef Name='Region' /><Value Type='Lookup'>" + regions + "</Value></Eq></Where>";
      SPListItemCollection items = list.GetItems(query);
      DataTable dt = items.GetDataTable();
      if (dt != null)
      {
         if (dt.Rows.Count > 0)
         {
            grdCountry.DataSource = dt;
            grdCountry.DataBind();
         }
      }
      else if (string.IsNullOrEmpty(regions))
      {
         dt = null;
         grdCountry.DataSource = dt;
         grdCountry.DataBind();
      }
      //DropDownList.SelectedIndex = 0;
   }
}

Step 13 : Deploy the solution to your specified site.

Step 14 : Create a page inside the sitepage library and add both webparts.



Step 15 : Add the connection between both webparts.



Step 16 : Select region from the provider webpart and you will find the result in the consumer webpart as below.



Conclusion

In this article I explained step-by-step how to create a connected webpart in SharePoint 2010 and send parameters from one webpart to another.

Up Next
    Ebook Download
    View all
    Learn
    View all