Freigeben über


Adding user control to SharePoint 2007 (MOSS/WSS) Web Part and handling events in there

View the updated one: Part 2 - Adding user control to SharePoint 2007 (MOSS/WSS) Web Part and handling events in there - Step by Step with task pane properties.

 

Requirement: I have a Web User Control where I added one textbox and a button. Now I wanted to add this user control into a SharePoint Web Part. After adding this Web Part to any page, if I click the button, there should be a text “Hello World” in the Text Box.

Steps:

  1. Create a blank web application and add a web user control (name WebUserControl.ascx) into it. While adding the user control, uncheck the "Place code in a separate file" option.
  2. Add one TextField and a Button to the user control. The ids of these controls are TextBox1 and Button1 respectively.
  3. Now copy this user control to a folder (wuc) under your virtual host (Web Application) path. In my case it is: “C:\Inetpub\wwwroot\wss\VirtualDirectories\80\wuc\”.
  4. Now create a web part application using Visual Studio SharePoint Web Part template. Here is the code for the web part:

using System;

using System.Runtime.InteropServices;

using System.Web.UI;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Serialization;

using Microsoft.SharePoint;

using Microsoft.SharePoint.WebControls;

using Microsoft.SharePoint.WebPartPages;

namespace wucwp

{

    [Guid("ee818646-e872-455c-a857-6e64e513539b")]

    public class wucwp : System.Web.UI.WebControls.WebParts.WebPart

    {

        UserControl userControl;

        System.Web.UI.WebControls.TextBox txtField;

        System.Web.UI.WebControls.Button showButton;

        public wucwp()

        {

            this.ExportMode = WebPartExportMode.All;

        }

        protected override void Render(HtmlTextWriter writer)

        {

            // TODO: add custom rendering code here.

            // writer.Write("Output HTML");

            userControl.RenderControl(writer);

        }

        protected override void CreateChildControls()

        {

            base.CreateChildControls();

            userControl = (UserControl) Page.LoadControl(@"/wuc/WebUserControl.ascx");

            txtField = (System.Web.UI.WebControls.TextBox) this.userControl.FindControl("TextBox1");

            showButton = (System.Web.UI.WebControls.Button) this.userControl.FindControl("Button1");

            showButton.Click += new EventHandler(showButton_Click);

            Controls.Add(userControl);

        }

        void showButton_Click(object sender, EventArgs e)

        {

            //throw new Exception("The method or operation is not implemented.");

            txtField.Text = "Hello World";

        }

    }

}

Now deploy this web part and add it to any page of your site and this should work as expected.

 

 

Update Note: One minor modification. It is better to put the .WebUserControl.ascx file under 12-Hive\TEMPLATE\CONTROLTEMPLATES folder, and access it as userControl = (UserControl) Page.LoadControl(@"/_controltemplates/WebUserControl.ascx");

 

Thanks Inge for your inputs.

Comments

  • Anonymous
    November 30, 2007
    Requirement: I have a Web User Control where I added one textbox and a button. Now I wanted to add this

  • Anonymous
    November 30, 2007
    Hi, I have a Windows User Control(Textbox+Button) which i am adding to a web part. It would be great if you could tell me how to handle the windows user control button click event in the webpart?

  • Anonymous
    December 03, 2007
    First, is there a reason why you did not copy the temlate to the _controltemplates folder? It would then be accessible from any Sharepoint site. Second, did you skip not having a seperate codebehind file because of CAS issues? This can be fixed by setting setting Full trust and copying the codebehind assembly to the bin catalog.

  • Anonymous
    December 26, 2007
    this help a lot for me, this is very good approach and code was very useful simple and error free Regards, Fareed Nizami Software Engineer http://www.softechww.com fareed.nizami@softechww.com

  • Anonymous
    January 07, 2008
    Has anybody knows how to called UserControl Property Attributes in Webparts ? Because I want to set the customise property attributes for the usercontrol while loading usercontrol in webpartts.

  • Anonymous
    January 21, 2008
    Hi, I have a custom property defined in User control. I want to set the user control property value from within Webpart, which is loading the user control. When I tried that, I am not getting the property shown in the webpart while accessing the user control. Is there a way to achieve this. Regards.

  • Anonymous
    January 22, 2008
    Do u have idea on how to load the Sharepoint user control like ( ToolBar.ascx ) in custom webpart Thanks

  • Anonymous
    January 23, 2008
    I tried this but I got my user control rendering in the upper left quadrant of the Sharepoint page, not in the web part.  I am overriding CreateChildControls and RenderContents as mentioned above.  Do I need to use code similar to this?: Control uc = this.LoadControl(@"webpartsCompanyNews.ascx"); uc.ID = "wp2"; GenericWebPart wp2 = WebPartManager1.CreateWebPart(uc); WebPartManager1.AddWebPart(wp2, WebPartZone1, 1); Another question... if I use GenericWebPart and WebPartManager.CreateWebPart (and AddWebPart), would Controls.Add(userControl) even work anymore (as far as wiring up the user controls events to the Page)? Would I then need to grab a reference to every control within my user control and add an event in my web part if I wanted to respond to a button click within my user control (assuming the button click event in my user control gathers all the inputs from all the controls within the user control)? Sorry for being wordy, but I'm frazzled beyond belief right now and am in dire need of quick answers to all the questions I laid out in my post.  I would be glad to return the favor to anyone who helped me out. Thank you.

  • Anonymous
    January 23, 2008
    this.ExportMode = WebPartExportMode.All; error ?

  • Anonymous
    January 24, 2008
    I follow the code above when I import the .dwp in webpartzone I got this error Unable to add selected web part(s). The Namespace.classname class does not derive from the Microsoft.SharePoint.WebPartPages.WebPart class and therefore cannot be imported or used in a WebPartZone control. If you inherit Microsoft.SharePoint.WebPartPages.WebPart  instead of webcontrol it works but events are not fired.

  • Anonymous
    January 28, 2008
    hi it's really good article..... thanks..

  • Anonymous
    February 11, 2008
    I have a question.. What if I have a event declared in the User Control, and raise the event. How can I subscribe for that event when you are dynamically loading the control. Thanks in advance.

  • Anonymous
    February 13, 2008
    I am brand new to ASP, SharePoint and only moderately acquainted with C# but not in the ASP or SharePoint arena at all.  This may be why I cannot get this example to work. I have copied the steps exactly as they are laid out above.  I changed the LoadControl to point to "/_controltemplates/WebUserContol.ascx" as suggested.  That file is located at C:Program FilesCommon FilesMicrosoft Sharedweb server extensions12TEMPLATECONTROLTEMPLATES on the server. Everything is being tested and debugged on the server. When I deploy the web part from VS and then go to the Site Settings in SharePoint and click on Web Parts in the Gallery section I see my new web part is added.  If I click on it to see a preview of it I always get an error.  That error changes from one version to another.  Most of the time it is "Unknown Error" but I have seen "File not found". Any suggestions? Thanks, Robert

  • Anonymous
    February 25, 2008
    The comment has been removed

  • Anonymous
    February 26, 2008
    Hi, could you please let me know how a user control with a Databound dropdown list could be displayed? I mean the dropdown list gets data from a database. Do I need to create an instance of the datasource again in the class library file? Could you please help Thanks Aditi

  • Anonymous
    February 29, 2008
    Hi , I am trying to create a user control in the visual studio and i am having a code behind file where i am accessing the sharepoint list via the object model. i am  copying my user control to the ControlTamplate folde and the sub control folder of my project specific. I added the src  in the page as "~/Controls/<MY Project Control Folder>/Control.ascx. I am not able to render this page since . it is giving me error for the src of the control. Can some one please suggest the way to consume the user control in the application page of the sharepoint site. Thanks in Advance

  • Anonymous
    April 10, 2008
    The comment has been removed

  • Anonymous
    May 02, 2008
    Button click event not getting fired. Any help...

  • Anonymous
    May 26, 2008
    i'm the beginer of sharepoint. May I know how to make the connection to database and how to insert the "txtField.Text" once click the "showButton" using stored procedure? Your help will be appreciated. Thx.

  • Anonymous
    May 27, 2008
    Hi, There are so many ways to develope webpart e.g using smartpart, using user control without codebehind code, using user control with code behing, using webpart. What is the best preactice for developing webpart. Any help.

  • Anonymous
    May 27, 2008
    In the ASP.NET world, database connection strings are typically stored in the web.config of the application.  This doesn't seem to be the case with SharePoint. Can anybody tell me how this scenario is handled in SharePoint? Your help will be appreciated.

  • Anonymous
    July 10, 2008
    the events of the controls present in the webpart are not firig in MOSS as i am attached the events in OnInit please tell us how to fire the events.

  • Anonymous
    July 17, 2008
    Since my post “ Adding user control to SharePoint 2007 (MOSS/WSS) Web Part and handling events in there

  • Anonymous
    August 08, 2008
    Since my post “ Adding user control to SharePoint 2007 (MOSS/WSS) Web Part and handling events in there

  • Anonymous
    September 24, 2008
    Hi Pranab,           It was such a really nice article which i was looking for. Pranab, It is good when we have one o r two usercontrols but, how can we associate almost 15 usercontrols into it and make easy navigation among all user controls in a single web part. One more that I would like to take in your consideration that if we go this way then it would be hard to handle the events of all user controls on single web part.        Kindly advise me. I have to implement 15 user controls into single web part. Thanks & Regards, Abhishek Verma New Delhi mailto: abhishekv@ibilttechnologies.com

  • Anonymous
    April 16, 2009
    Hi, I would like to know how can I deploy my webpart with webusercontrols by the packeg created with the Sharepoint WebPart Project Tnx

  • Anonymous
    July 08, 2009
    This works fine but now I'm to the point of creating connections between controls like this and I'm wondering if there are any best practices or pointers.  I'm doing the majority of the work in the inherited class for the user control - data binding, handling control events etc.  The web part is pretty dumb.  It's really just a host for the user control.  I'm assuming I can't simply define Connection Consumer / Connection Provider methods inside of the user control (unless the web part class has some sort of mechanism for searching it's sub controls for connection points).  So what do a do?  Do I expose some methods from my user control that the web part can use to satisfy the connection?  For example, the user control has a grid view that is bound to data that it retrieves internally (the web part class knows nothing about it).  But now I want to expose that data for a connection.

  • Anonymous
    January 03, 2010
    This helps me only for path, but good example

  • Anonymous
    January 06, 2010
    hi, i am nesting the  2 usercontrol. but when i try to access textbox.text value, first time it retrun me blank value and 2nd time returning me the actual value. Can u guide why this problem occuring. listing... ctrlUser = (UserControl)this.Page.LoadControl(strControlPath1);                    GoalControl =(UserControl) this.Page.LoadControl(strControlPath2); this.Controls.Add(ctrlUser); PnlCustomer.Controls.Add(GoalControl); if (ViewState["Obj"].ToString() == "Internal")                    PnlInternal.Controls.Add(GoalControl);                if (ViewState["Obj"].ToString() == "Finance")                    PnlFinance.Controls.Add(GoalControl);                if (ViewState["Obj"].ToString() == "Org")                    PnlOrg.Controls.Add(GoalControl); txtObj = PnlCustomer.Controls[0].FindControl("txtObj") as TextBox; but this txtObj, first time returning blank value. Since i am switiching the GoalControl to different Placeholder during run time.

  • Anonymous
    July 29, 2010
    The comment has been removed