Hello All,
In a following post we will see how to create custom
property to a Visual webpart and access them in code.
Generally we can achieve this in 2 ways.
In Current post we will look at the 1st Method:
Step 1: Create One Sample Empty SharePoint Project and add
Web part to the Solution.
Step 2: Navigate to “.cs” file of your webpart. In Our case “SampleWebPart.cs”
is the file.
Note: In Our Sample Program we are adding only one Custom
Property to the webpart.You can add as per your requirement.
Following code needs to be add in webpart.cs file.
[WebBrowsable(true)]
[WebDisplayName("ListName")]
[WebDescription("List Name to Get the
Details")]
[Personalizable(PersonalizationScope.User)]
[DefaultValue("Please Configure the
Web Part")]
[Category("Custom
Configuration")]
public String ListName
{
get;
set;
}
Change the code in below method:
protected override void CreateChildControls()
{
//Control
control = Page.LoadControl(_ascxPath);
SampleWebPartUserControl control = SampleWebPartUserControl)Page.LoadControl(_ascxPath);
control.parentwebpart = this;
Controls.Add(control);
}
Accessing the Property:
Navigate to the “.ascx.cs” file of the webpart.
Declare the below property.
public SampleWebPart parentwebpart { get; set; }
We Can access our custom property as below.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (!string.IsNullOrEmpty(this.parentwebpart.ListName))
{
string listName = this.parentwebpart.ListName;
lblListName.Text =
listName;
}
}
}
Navigate to Page and Add the Web part which was developed
earlier.
Click on Edit Page and Edit Web Part Properties.
Scroll down the Property section there you will find
Custom Configuration section, here we need to specify the List Name.
Final Out Come you can see as below.
Note: In above example just I am reading the property
specified by user and bind the same to the label.
You can download solution from the below link.The solution is developed on VS 2013 Ultimate.
Nice post,
ReplyDelete