It’s an easy two-step process:
First we will add a public variable 'ListName' to the VisualWebPart's UserControl, *.ascx.cs
public string ListName { get; set; }
We do this in preparation, as we need to use the value here in the usercontrol code.
All Code:
using System; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; namespace SomeVisualWebPart.VisualWebPart1 { public partial class VisualWebPart1UserControl : UserControl { public string ListName { get; set; } protected void Page_Load(object sender, EventArgs e) { // use ListName } } }
The second and final step is to add code to the WebPart to add the custom property to it.
We'll start by adding a personalizable public variable to the WebParts *.cs code.
[Personalizable(PersonalizationScope.Shared), WebBrowsable(true), WebDisplayName("List Name"), WebDescription("The name of the List to display."), Category("Custom Property")] public string ListName { get; set; }
Then under the CreateChildControls section, change your code to implement 'controls' as your usercontrol and set the variable(s) needed to be passed to the usercontrol.
VisualWebPart1UserControl control = (VisualWebPart1UserControl)Page.LoadControl(_ascxPath); control.ListName = this.ListName; Controls.Add(control);
All Code:
using System; using System; using System.ComponentModel; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using Microsoft.SharePoint; using Microsoft.SharePoint.WebControls; namespace SomeVisualWebPart.VisualWebPart1 { [ToolboxItemAttribute(false)] public class VisualWebPart1 : WebPart { // Visual Studio might automatically update this path when you change the Visual Web Part project item. private const string _ascxPath = @"~/_CONTROLTEMPLATES/SomeVisualWebPart/VisualWebPart1/VisualWebPart1UserControl.ascx"; [Personalizable(PersonalizationScope.Shared), WebBrowsable(true), WebDisplayName("List Name"), WebDescription("The name of the List to display."), Category("Custom Property")] public string ListName { get; set; } protected override void CreateChildControls() { VisualWebPart1UserControl control = (VisualWebPart1UserControl)Page.LoadControl(_ascxPath); control.ListName = this.ListName; Controls.Add(control); } } }
Result:
No comments:
Post a Comment