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 (30)

  1. Requirement: I have a Web User Control where I added one textbox and a button. Now I wanted to add this

  2. Pradeep says:

    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?

  3. Inge Henriksen says:

    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.

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

  5. FarukDange says:

    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.

  6. mswin says:

    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.

  7. Sandeep says:

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

    Thanks

  8. Christopher Noyes says:

    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.

  9. thanh khoa says:

    this.ExportMode = WebPartExportMode.All; error ?

  10. Joe says:

    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.

  11. vardhan says:

    hi

    it’s really good article…..

    thanks..

  12. Mano Mangaldas says:

    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.

  13. Robert Lawson says:

    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

  14. m.kashif says:

    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

  15. Aditi says:

    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

  16. Sunil Upadhyay says:

    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

  17. Sanjay Patel says:

    Hi Buddy,

    I am following the same steps…My usercontrol is there in the "12-HiveTEMPLATECONTROLTEMPLATES" folder but still i am getting the following file not found exception…Can u please suggest me the reason/solution??? Any help would be appreciated. My email id is sanjay.patel@conchango.com , software.sanjay@gmail.com

    waiting for ur reply…Thanks in advance…Sanjay Patel

    The file ‘/_controltemplates/TestUserControl.ascx’ does not exist.   at System.Web.UI.Util.CheckVirtualFileExists(VirtualPath virtualPath)

      at System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile)

      at System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile)

      at System.Web.UI.TemplateControl.LoadControl(VirtualPath virtualPath)

      at System.Web.UI.TemplateControl.LoadControl(String virtualPath)

      at ProviderAndConsumerWebparts.ProviderWebPart.CreateChildControls() in C:conchangoSanjayRDProviderAndConsumerWebpartsProviderAndConsumerWebpartsProviderAndConsumerWebparts.cs:line 128

      at System.Web.UI.Control.EnsureChildControls()

      at System.Web.UI.Control.PreRenderRecursiveInternal()

      at System.Web.UI.WebControls.WebParts.WebPart.PreRenderRecursiveInternal()

      at System.Web.UI.Control.PreRenderRecursiveInternal()

      at System.Web.UI.Control.PreRenderRecursiveInternal()

      at System.Web.UI.Control.PreRenderRecursiveInternal()

      at System.Web.UI.Control.PreRenderRecursiveInternal()

      at System.Web.UI.Control.PreRenderRecursiveInternal()

      at System.Web.UI.Control.PreRenderRecursiveInternal()

      at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

  18. Pankaj says:

    Button click event not getting fired.

    Any help…

  19. nseng7630@hotmail.com says:

    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.

  20. Pankaj says:

    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.

  21. Ray Ng says:

    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.

  22. Raju says:

    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.

  23. Since my post “ Adding user control to SharePoint 2007 (MOSS/WSS) Web Part and handling events in there

  24. Since my post “ Adding user control to SharePoint 2007 (MOSS/WSS) Web Part and handling events in there

  25. Abhishek verma says:

    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

  26. Salvo Di Fazio says:

    Hi,

    I would like to know how can I deploy my webpart with webusercontrols by the packeg created with the Sharepoint WebPart Project

    Tnx

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

  28. suhail says:

    This helps me only for path, but good example

  29. aashita says:

    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.

  30. Satish V says:

    Hi..

    I am new to sharepoint.. Nice and useful example.

    Rather than handling events in the webpart. Cant we handle events in WebUserControl.ascx.cs and keep in a dll file?