Sharing WebPart and User Control Properties

When creating a Visual WebPart, sometimes you want the main functionality to be contained within the user control and not the WebPart, so that, for example, you can use the WebPart on multiple pages, one where the WebPart is hosted and users can edit the properties and another where only the user control is loaded and no WebPart manager, or WebPart zones, are available to allow editing of the properties.

In the later case, the properties defined in the WebPart would either be set to default values or be retrieved from the query string.

Now, how to setup the user control to receive the WebPart’s property values when contained in a WebPart?

Take the following declaration within the WebPart class:

public class ExampleVisualWebPart : WebPart
{
	// Other methods and properties excluded for brevity
 
	[Personalizable(PersonalizationScope.Shared), WebBrowsable(true)]
	public string ExampleProperty { get; set; }
}

The first thing to do is to add a new public property to the user control using the WebPart as the object type:

public ExampleVisualWebPart ParentWebPartControl { get; set; }

and then create the same property declared in the WebPart for the user control:

private string _customProperty;
 
public string ExampleProperty 
{
	get
	{
		if (ParentWebPartControl != null)
			return ParentWebPartControl .CustomProperty;
 
		return _customProperty;
	}
	set
	{
		if (ParentWebPartControl != null)
			ParentWebPartControl .CustomProperty = value;
 
		_customProperty = value;
	}
}

Lastly, back in the WebPart class, change the CreateChildControls method to:

protected override void CreateChildControls()
{
	ExampleVisualWebPartUserControl userControl = new ExampleVisualWebPartUserControl { ID = "exampleVisualWebPartUserControl", ParentWebPartControl = this };
	Controls.Add(userControl);
}

or

protected override void CreateChildControls()
{
	ExampleVisualWebPartUserControl userControl = Page.LoadControl(_ascxPath) as ExampleVisualWebPartUserControl;
	userControl.ParentWebPartControl = this;
	Controls.Add(userControl);
}

This will load the user control and set the ParentWebPartControl to the current WebPart, allowing the user control to read the property values defined by the WebPart. When there is no parent WebPart, the user control will simply read the local value contained within itself.

You can easily extend this to read from a query string when this is the case.

2 comments

  1. Abraham says:

    Your last part where you are setting “ParentWebPartControl” to the current webpart,
    the code should be usercontrol.ParentWebPartControl = this;

Leave a Reply

Your email address will not be published. Required fields are marked *

Solve the maths problem shown below before posting: *

Follow

Get every new post delivered to your Inbox

Join other followers: