Search code examples
sharepointweb-parts

SharePoint 2013Visual WebPart with custom properties


Solved. Read on...

I can copy the code from this MSDN aricle 1:1 and it does not work. I cannot see any custom property in the web part properties. Although there is no "Miscellaneous" category. There's only Appearance, Layout and Advanced.

namespace Tts.CareersPortal.Web.CareersPortal.Fn.WebParts.NewContactTeaserWebPart
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Web.UI;
    using System.Web.UI.WebControls.WebParts;
    using MyNameSpace.NewContactTeaserWebPart;

    public partial class NewContactTeaserWebPartUserControl : UserControl
    {
        private int _contactTeaserCount;

        [Category("Extended Settings"),
        Personalizable(PersonalizationScope.Shared),
        WebBrowsable(true),
        WebDisplayName("Sample Text"),
        WebDescription("Please Enter a Sample Text")]
        public int ContactTeaserTeaserCount
        {
            get
            {
                return _contactTeaserCount;
            }
            set
            {
                _contactTeaserCount = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            IEnumerable<MyContact> contacts = LoadContactProperties();

            Repeater1.DataSource = contacts;
            Repeater1.DataBind();
        }

        private IEnumerable<MyContact> LoadContactProperties()
        {
            ContactFinder contactFinder = new ContactFinder(ContactTeaserTeaserCount);

            IEnumerable<MyContact> result = contactFinder.GetContact();
            return result;
        }
    }
}

Solution: I was adding the web part property to the wrong class file :-/ You have to add it to the webpart - not the user control. To pass along the webpart properties to the user control I recommend this following approach - others will work too.

Does not work. Any ideas?


Solution

  • If you need help in creating a visual webpart in SharePoint 2010 using C#, follow this link

    If you need help with webpart property alone, try the following code:

    public static string SampleText;
    [Category("Extended Settings"),
    Personalizable(PersonalizationScope.Shared),
    WebBrowsable(true),
    WebDisplayName("Sample Text"),
    WebDescription("Please Enter a Sample Text")]
    public string _SampleText
    {
        get { return SampleText; }
        set
        {
            // Sample Validation
            Regex oRegEx = new Regex("[a-zA-Z]+");
            if (!oRegEx.IsMatch(value))
                throw new Microsoft.SharePoint.WebPartPages.
                    WebPartPageUserException(
                    "Please enter alphabeth characters only");
            SampleText = value;
        }
    }
    

    Also find the following article helpful in the same: Custom webpart properties