Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I have created a visual web part containing the default user control. I want to access the custom property of the web part defined in the xml-file Mywebpart.webpart -CustomProperty- from the code-behind of the user control, but don´t know how.

<?xml version="1.0" encoding="utf-8"?>
<webParts>
<webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
<metaData>
  <type name="foo" />
  <importErrorMessage>$Resources:core,ImportErrorMessage;</importErrorMessage>
</metaData>
<data>
  <properties>
      <property name="Title" type="string">mywebpart</property>
      <property name="Description" type="string">a nice visual web part</property> 
      <property name="CustomProperty" type="string">foo foo</property>         
  </properties>
</data>

Up to now, I can only access Title and Description:

Mywebpart parent = (Mywebpart)Parent;
string title = parent.Title;
share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

The User Control is being inserted into the control collection of the "real" Web Part, this enables you to get hold of the "real" Web Part though the Parent property of the User Control. If all you want to access is the standard properties of the Web Part you can just cast Parent to WebPart, but if you have introduced custom properties then you of course need to case Parent to your WebPart type.

Here is a very interesting example which outputs the title.

protected override void CreateChildControls()
{
    base.CreateChildControls();
    var webPart = (WebPart)Parent;
    var title = webPart.Title;
    Controls.Add(new LiteralControl(title));
}

As you want to access a Custom Property you first have to add that custom property to the "real" Web Part like this:

[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[WebDisplayName("Custom Property")]
[WebDescription("Here you can enter value for custom property")]
public string CustomProperty { get; set; } 

The WebBrowsable attribute control whether users are allowed to change the property though the UI.

You then need to remove the web part from the page and add it again as it hasn't stored the value from the .webpart file in the instance on the page.

share|improve this answer
    
Thanks for answering. No, I need to access a custom property (see update). I have cast to Mywebpart, how do I get to it? –  AGuyCalledGerald Jul 13 '12 at 11:55
    
Answer updated with info about how to add a custom property –  Per Jakobsen Jul 13 '12 at 13:06
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.