Showing posts with label Webparts. Show all posts
Showing posts with label Webparts. Show all posts

Oct 2, 2009

Creating a Custom Toolpart for webpart

Webpart comes with a default tool part which contains the configuration settings for the webpart. But often we have requirement to create the custom toolpart for the webpart having certain .net controls like dropdown list ,treeview etc which fetches data from the list or any other source and performs certain functionality based on the logic.

Webpart will look like this



Here is step by step process for creating webpart with custom toolpart:

1)      Open visual studio
2)      Create a new project with type class library
3)      Inherit the class with  Microsoft.SharePoint.WebPartPages.WebPart class

Below is the code for the webpart class


----------------------------------------------------------------------


using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;


namespace CustomToolPartWP
{
    public class CustomWebPart : Microsoft.SharePoint.WebPartPages.WebPart
    {
        private string ddlvalue = string.Empty;


        [Browsable(false), Category("Miscellaneous"),
        WebPartStorage(Storage.Personal),
        FriendlyName("ListValue"), Description("Text Property")]
        public string DropDownListValue
        {
            get
            {
                return ddlvalue;
            }


            set
            {
                ddlvalue = value;
            }
        }


        //  Gets the custom tool parts for this Web Part by
        /// overriding the GetToolParts method of the WebPart
        /// base class. You must implement custom tool parts in
        /// a separate class that derives from
        /// Microsoft.SharePoint.WebPartPages.ToolPart.
        ///
        ///
        /// An array of references to ToolPart objects.
        ///
        public override ToolPart[] GetToolParts()
        {
            ToolPart[] toolparts = new ToolPart[3];
            WebPartToolPart wptp = new WebPartToolPart();
            CustomPropertyToolPart custom = new CustomPropertyToolPart();
            toolparts[0] = custom;
            toolparts[1] = wptp;


            // This is the custom ToolPart.
            toolparts[2] = new CustomToolPartWP.CustomToolPart();


            return toolparts;
        }


        /// Render this Web Part to the output parameter specified.
        /// The HTML writer to write out to
            protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);
            writer.Write("Value Selected from dropdown is " + this.ddlvalue +
");
        } 
    }
}
------------------------------------------------------------------
Lets discuss some important features of the webpart .Here we have declared one “DropDownListValue” ,it has some attributes like
a)      Browsable : To appear this property in the wepart
b)      Category: It shows the label name under which our custom control should render
c)      WebPartStorage : There are two types of storage .One is personal ,this means that the value stored are specific to the logged in user ,other is shared ,in this saved value will be visible to all the users.


Once the webpart is done we need to add the class for toolpart which contains the code for custom toolpart. Follow these steps:
1)      Add class to the solution
2)      Inherit this class with Microsoft.SharePoint.WebPartPages.ToolPart

This is the sample code for the Toolpart which renders once dropdown list and selecting some value and clicking on Apply or Ok  sets the value in the webpart.
------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;


namespace CustomToolPartWP
{
    ///
    /// Description of the toolpart. Override the GetToolParts method
    /// in your Web Part class to invoke this toolpart. To establish
    /// a reference to the Web Part the user has selected, use the
    /// ParentToolPane.SelectedWebPart property.
        class CustomToolPart : Microsoft.SharePoint.WebPartPages.ToolPart
    {
        private string inputname;
        DropDownList dropdownList;


            // an event handler for the Init event
        private void CustomToolPart_Init(object sender,
                  System.EventArgs e )
            {
                  inputname = this.UniqueID + "message";
            }


            ///
            /// Constructor for the class. A great place to set Set
            /// default values for additional base class properties
            /// here.
            ///


        public CustomToolPart()
            {
                  // Set default properties
                  this.Title="Select Value";
            this.Init += new EventHandler(CustomToolPart_Init);
            }
            ///   Called by the tool pane to apply property changes to
            /// the selected Web Part.
           public override void ApplyChanges()
            {
                  CustomWebPart customWP = (CustomWebPart)
                  this.ParentToolPane.SelectedWebPart;
                 
                  // Send the custom text to the Web Part.
            customWP.DropDownListValue = dropdownList.SelectedItem.Value;
            }


        protected override void CreateChildControls()
        {
            //base.CreateChildControls();
            dropdownList = new DropDownList();
            dropdownList.Items.Add("item1");
            dropdownList.Items.Add("item2");
            dropdownList.Items.Add("item3");
            dropdownList.Items.Add("item4");
            CustomWebPart customWP = (CustomWebPart)
            this.ParentToolPane.SelectedWebPart;
           
            dropdownList.Items.FindByText(customWP.DropDownListValue).Selected = true;


            this.Controls.Add(dropdownList);
        }
            ///   If the ApplyChanges method succeeds, this method is
            /// called by the tool pane to refresh the specified
            /// property values in the toolpart user interface.
            public override void SyncChanges()
            {
                  // sync with the new property changes here
            CustomWebPart customWP = (CustomWebPart)
                  this.ParentToolPane.SelectedWebPart;
            customWP.DropDownListValue = dropdownList.SelectedItem.Value;
            }
           
            ///   Called by the tool pane if the user discards changes
            /// to the selected Web Part.
            public override void CancelChanges()
            {
            }
            /// Render this Tool part to the output parameter
            /// specified.
            /// The HTML writer to write out to
            protected override void RenderToolPart(HtmlTextWriter output)
            {
                  // Establish a reference to the Web Part.
                  CustomWebPart customWebPart = (CustomWebPart)
                  this.ParentToolPane.SelectedWebPart;
                  output.Write("Select value from drop down: ");
            dropdownList.RenderControl(output);
            }
    }
}
 ------------------------------------------------------------------------------------

After this compile the solution and deploy the webpart and put the dll in GAC or the bin folder of the webapplication

And your webpart is ready to use with custom toolpart.
 There is a very good artilce on MSDN to create custom toolpart.
If you have queries than do post.

Your job is done J
Enjoy!!!

Sep 19, 2009

Limiting length of Multiline textbox(inside webpart) through javascript

Here the requirement is to limit the maxlength of multiline text box in webpart .This seems to be very simple problem,just set the property of MaxLength property of TextBox to some no,but when somehow this property does not work with Multiline Text Box..may be there will be some fix in future release.

So we fix this problem using java script

Add this javascript in the CreateChildControl method.

Here is javascript for this :

----------------------------------------------------------

StringBuilder javascript = new StringBuilder();

javascript.AppendLine("<script type='text/javascript'>");

javascript.AppendLine("function Validation(evt,maxLength)");

javascript.AppendLine("{");

javascript.AppendLine("if(evt.value.length > maxLength)");

javascript.AppendLine("{");

javascript.AppendLine("alert('Maximum 255 characters allowed');");

javascript.AppendLine("evt.value = evt.value.substring(0,maxLength);");

javascript.AppendLine("}");

javascript.AppendLine("}");

javascript.AppendLine("</script>");

if (javascript != null)

{

Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "javascriptcode", javascript.ToString());

}

-------------------------------------------------------------

In above code we have written the java script and registered the client script in the page.Now we need to add this javascript event in the multiline textbox

-------------------------------------------------------------txtMultilineTextBox.Attributes.Add("onKeyDown", "Validation(this, 255)");

----------------------------------------------------------------
Now we have added the event in the text box for "onKeyDown" event .So whenever user exceed 255 characters in the text box this event will fire and limit the length.

Programmatically Adding List viewer Web part(for document Library) on the page

Objective is to add the listviewer web part on the page programmatically. I have a document library for which i want to add the list viewer web part on any page.

Create a console application and paste the code

Code snippet

class Program

{

static void Main(string[] args)

{

SPSite site = new SPSite(”Site Url”);

SPWeb oSubWeb = site.OpenWeb();

oSubWeb.AllowUnsafeUpdates = true;

//Get the object of the page as SPFile on which we need to add the listviewer webpart

SPFile oFile = oSubWeb.GetFile(”default.aspx”);

//Create the object SPLimitedWebPart Manager

SPLimitedWebPartManager oWebPM = oFile.GetLimitedWebPartManager(PersonalizationScope.Shared);

//Get the object of the list of which we are creatin the list viewer webpart

SPList oSubSiteList = oSubWeb.Lists["Shared Documents"];

//Create the object of ListViewer webpart

ListViewWebPart oListViewWP = new ListViewWebPart();

//Set the properties of the webpart

oListViewWP.ChromeType = PartChromeType.TitleOnly;

oListViewWP.Title = “Shared Documents”;

oListViewWP.ListName = oSubSiteList.ID.ToString(”B”).ToUpper();

//Define the zone in which webparts need to be added

oWebPM.AddWebPart(oListViewWP, “Zone 1″, 1);

}

}

Your job is done….

Enjoy!!!

If you find this post useful then please post your comments

Using SP Grid View inside Webpart

In this post I am using SPGrid view inside a webpart.

First we need to initialize the SPGrid view control in the Create Child control mehod and specify its properties

Use this code inside CreateChildControl method

—————————————————————

//Initialize the control

SPGrid CustomGrid;

CustomGrid = new SPGridView();

CustomGrid.Width = Unit.Pixel(700);

this.CustomGrid.ID = “Customgrid”;

//Specifying the Eventhandler for Paging

this.CustomGrid.PageIndexChanging += new GridViewPageEventHandler(CustomGrid_PageIndexChanging);

this.CustomGrid.AutoGenerateColumns = false;

//Specifying the grid properties

this.CustomGrid.PageSize = 10;

this.CustomGrid.BackColor = System.Drawing.Color.White;

this.CustomGrid.GridLines = GridLines.Horizontal;

//Allowing Paging on the Grid

this.CustomGrid.AllowPaging = true;

this.CustomGrid.EnableViewState = true;

this.CustomGrid.TemplateControl = null;

//Creating Boundfields in the Grid view

BoundField DealName = new BoundField();

DealName.DataField = “Name”;

DealName.ItemStyle.Width = Unit.Percentage(30);

DealName.ItemStyle.Wrap = true;

this.Controls.Add(CustomGrid);

CustomGrid.PagerTemplate = null;

—————————————————————–

Once the declaration and initialization of control is done we need to define the pagination of the SPGrid

This is the method for the pagination event

—————————————————–

// Method for Page indexing

void CustomGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)

{

try

{

CustomGrid.PageIndex = e.NewPageIndex;

CustomGrid.DataBind();

}

catch (Exception ex)

{

}

}

Your job is done ..

Enjoy!!!