Monday 7 May 2012

Custom Properties in sharepoint 2010 visual webpart.



We know how to add custom properties in webpart. But is this same in visual webpart. No you have to create some more stuff for generate custom property in visual webpart.

Follow this steps for create custom properties in visual webpart.

  • Open Visual Studio 2010.
  • Create an "Empty SharePoint Project".
  • Right click on the solution and click on Add => New Item.
  • Select "Visual Web Part" template from SharePoint 2010 installed templates.

My visual webpart name is WordToPdf. You can see hole picture of my solution.







Now open wordToPdf.cs file and write following code within WordToPdf class.

        public string _DocLibraryName;
        [WebBrowsable(true),
        WebDisplayName("Document Library Name"),
        WebDescription(""),
        Personalizable(true),
        Category("Custom Properties"),
        DefaultValue("")]

        public string _Doclibrary
        {
            get { return _DocLibraryName; }
            set { _DocLibraryName = value; }

        }
Done your custom property added in custom properties group as string.
Now question is how we can get custom property value. So for that open WOrdToPdfUserControl.ascx.cs file and write following code

         public WordToPdf  WebPart { get; set; }  // here WordToPdf is your class name where custom property is defined

         this.WebPart = this.Parent as WordToPdf;
         var _Doclibrary = this.WebPart._Doclibrary;


OK you are able to get custom property value.In this example we only use string if you want to use droupdown list then add following code

       public enum ControlModes
        {
            Simple,
            Standard,
            Advanced
        }
        [DefaultValue(ControlModes.Standard)]
        [Description("Select a category from the dropdown list.")]
        [WebBrowsable(true)]
        [Personalizable()]
        [Category("Custom Properties")]

        public ControlModes ControlMode
        {
            get;
            set;
        }
If you want to add checkbox then use following code

 [DefaultValue(""),
        WebBrowsable(true),
        WebDisplayName("DisplayName"),
        WebDescription(""),
        Personalizable(true),
        Category("Custom Properties"),]
        public bool ch
        {
            get;
            set;
        }

You can also use DateTime and Integer. Hope this will help you
Thanks

4 comments:

  1. Great...........
    Thanx..This helped me lot........

    ReplyDelete
  2. Hey....I want to display Rich text editor instead of TextBox in Webpart Custom Property. Is this possible?

    ReplyDelete
  3. HI Vishal..

    i need to add multi line textbox in Webparts Custom properties..how..?
    plz give me some inputs..
    thqs...

    ReplyDelete