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

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

  • Comments 30

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.




  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



    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");




        protected override void 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);




        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.

Leave a Comment
  • Please add 3 and 6 and type the answer here:
  • Post
  • Requirement: I have a Web User Control where I added one textbox and a button. Now I wanted to add this

  • 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?

  • 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.

  • this help a lot for me, this is very good approach and code was very useful simple and error free


    Fareed Nizami

    Software Engineer

  • 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.

  • 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.


  • Do u have idea on how to load the Sharepoint user control like ( ToolBar.ascx ) in custom webpart


  • 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(@"webparts\CompanyNews.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.

  • this.ExportMode = WebPartExportMode.All; error ?

  • 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.

  • hi

    it's really good article.....


  • 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.

  • 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 Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\CONTROLTEMPLATES 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?



  • hi,

    i m using this code as it is, but the problem is that i add this user control to web part and click the nothing happened(in this case hello world not appread in text box)

    can anyone tell why my events are not firing.

    this event hanlding problem occuring in my all user controls.

    kindly help me urgently

    thanks in advance

  • 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



Page 1 of 2 (30 items) 12