How to change the properties of one web part from within another web part

   —   
This article shows you how to change the properties of a web part from within another.
In the .NET development model, it is quite common for developers to set the control's properties based on another control, for example, binding a GridView control based on the selected value of a drop down control. On occasion, you might need to do something similar with web parts within Kentico CMS. Kentico CMS considers web parts to be separate units, so there is no support for accessing another web part and changing its properties dynamically. This needs to be accomplished in the code behind of a given web part.

You can take advantage of CMS.GlobalHelper.RequestStockHelper class which gives you the ability to insert and get items into the HttpContext.Current.Items collection using Add/GetItem methods. You can add a reference to a web part to the collection and retrieve it in the code of another web part. Let me give you a simple example.
 
Let’s assume that you have two web parts: WebPartA and WebPartB. WebPartA contains a button:
 
<asp:Button runat="server" ID="btn" OnClick="btn_Click" />

 
Within the OnClick handler, you would like to change the Visible property of WebPartB.
 
First, you need to add the WebPartB web part into the HttpContext.Current.Items collection. You can do so in the OnInit method of WebPartB, as the following code demonstrates:
 
protected override void OnInit(EventArgs e)
{
   CMS.GlobalHelper.RequestStockHelper.Add("WebPartB", this);
   base.OnInit(e);
}

 
Now, you can access WebPartB in the OnClick handler of WebPartA and change its Visible property if necessary:
 
protected void btn_Click(object sender, EventArgs e)
{
  CMSAbstractWebPart WebPartB = RequestStockHelper.GetItem("WebPartB") as CMSAbstractWebPart;
  if (something)
  {
     WebPartB.Visible = false;
  }
}

 
Because each web part inherits from the CMSAbstractWebPart class, you can change any property provided by this class. To set or get custom web part properties, you might consider creating a custom interface which the web part would implement and would allow you to get/set the custom properties as the following code shows:
 
ICustomProperties WebPartB = CMS.GlobalHelper.RequestStockHelper.GetItem("WebPartB") as ICustomProperties;
if (something)
{
     WebPartB.CustomProperty = "Value";
}

-ml-


See also: Kentico CMS API

Applies to: Kentico CMS 6.0
Share this article on   LinkedIn