Click here to Skip to main content
Email Password   helpLost your password?

Introduction

Moss/WSS is so CMS popular currently. There are many thing can be which can be done and is modified at deep technology on that product.

Work with on that solution will ever be utilize webpart. But if we develop one webpart sometimes we do ever make same old things which is make coding webpart and load the usercontrol what does we want.

Background

This concept is similiar with SmartPart which you just create one webpart and then it can be used to load all your usercontrol without writing webpart again.

Using the Code

The listing code is like this:

  1. Write on your class solution like this. Please reference Microsoft.Sharepoint.dll component and System.Web.dll too.
using System;
using System.ComponentModel;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebPartPages;

namespace WebPartLib
{
    public class WebPartGeneral : Microsoft.SharePoint.WebPartPages.WebPart
    {
        private Control _childControl = null;
        private string _userControlVirtualPath = string.Empty;
        private string _errMessage = string.Empty;

        public WebPartGeneral()
        { }

        [
          Personalizable(),
          Category("Miscellaneous"),
          DefaultValue(""),
          WebBrowsable(true),
          WebDisplayName("User Control Virtual Path"),
          WebDescription("User Control Virtual Path")
        ]
        public string UserControlVirtualPath
        {
            get { return _userControlVirtualPath; }
            set { _userControlVirtualPath = value; }
        }

        protected override void RenderWebPart(HtmlTextWriter output)
        {
            if (_errMessage != string.Empty) output.Write(_errMessage);
            if (_userControlVirtualPath != string.Empty ||
                _userControlVirtualPath.Equals("") == false)
               RenderChildren(output);
        }

        protected override void RenderChildren(HtmlTextWriter output)
        {
            try
            {
                this.EnsureChildControls();
                if (this._childControl != null)
                    this._childControl.RenderControl(output);
            }
            catch (Exception ex)
            {
                _errMessage = string.Format(
                  "Exception Message (RenderWebPart) = {0}<br />", ex.Message);
            }
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            if (_userControlVirtualPath != string.Empty)
            {
                if (_childControl != null) return;
                _childControl = Page.LoadControl(_userControlVirtualPath);
                if (_childControl != null)
                    Controls.AddAt(0, _childControl);
            }
        }

        public override void Dispose()
        {
             
        }
    }
}
  1. After the solution already successfully compile and the put the binary into bin folder on your MOss/Wss site. After it also make one folder by which UserControls.

  1. Modify your web.config
eControl Assembly="WebPartLib, Version=1.0.0.0, Culture=neutral"
   Namespace="WebPartLib" TypeName="*" Safe="True"
   AllowRemoteDesigner="True" /> 

and change trust level from WSS_Minimal into Full.

<trust level="Full" originUrl="" /> 
  1. If Necesary you can client restart your IIS and the back to your site again and list the webpart into list of webpart

  2. Create new website solution and create a simple usercontrol and then copy all .ascx and .cs into UserControls folder
  3. Now you can utilize webpart and set the virtual path into your usercontrols and the simsalabim your webpart now load your usercontrol. You can create another usercontrol again and you can add your webpart again and set the usercontrols to load.

Points of Interest

As i mention before, Now every time you create a usercontrol you don't have to create another webpart. It's only use that webpart again and set path into that usercontrols.

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralGreat
Niccs
2:16 27 Nov '09  
Hi ! this is the best solution, I ever seen for user control.

Thanks a lot
Nics
GeneralGetting error while loading the user control
am20an
0:47 23 Oct '09  
I am able to use your code. The webpart is very well shown in the add web part section as "WebPartGeneral" but when i try to load my control by giving the path in its's miscelleneos section, i am getting an error:-
"An unexpected error has occurred."
I am specifying the path as:-
/usercontrol/wpSample1.ascx

If my site is under X port then i need to make folder named as usercontrol. I have done that also. Copied all .ascx and .cs files into usercontrol folder but no luck.

Please help.
QuestionNested LoadControl
guaneme
10:01 5 May '09  
Hi.

Great article. However, we had problems with the following scenario:

We load control AAA with the posted code and it works. But control AAA dynamicly loads controls BBB and CCC using its inherited LoadControl() function. An error saying "File BBB.ascx does not exist." But, if you try to load BBB or CCC within your code it works perfectly.

Did you have the same behavior? How did you manage to solve it?

Thanks in advance.

Carlos Guaneme

AnswerRe: Nested LoadControl
Gyan Singh
0:21 28 Aug '09  
Did you get the solution for this? I also have same problem...

I have created some user controls. I have dynamically loaded one usercontrol say "ChildControl.ascx" in another user control say "ParentControl.ascx" using the following code:

Dim tempControl As New Control
tempControl = LoadControl("~/folder/folder2/ChildControl.ascx")
Dim objChild As ChildControl = TryCast(tempControl, ChildControl)

I have converted the user controls into custom controls. Then I am using all these control as you mentioned in this post.
But I am getting the following error while the parent control is loading the child control dynamically:

The file '/folder/folder2/ChildControl.ascx' does not exist.

How should I solve this problem?

I also want to generate output to single assembly/dll for all the user controls, and I will use this single dll to register any usercontrol. how is it possible?

Thanks,
GeneralI'm getting error
elnone85
15:40 20 Apr '09  
Hi,
Thank you very much indeed about this article.
Everything is working fine with me until modify the webpart to put the user control virtual path I get "An unexpected error has occurred." and I can't determine the reason of that error. I thought the reason is the path but I added onec this path "/usercontrols/wpSample1.ascx" and another try with this path "~/usercontrols/wpSample1.ascx" but same result.

Do you have any advise what shall I do?

Regards,
GeneralI have a question please..
Oslec
23:33 19 Apr '09  
Hi Agusto, my question maybe out of scope but please.. Is it possible to create an "CreateUserWizard" control then load it to custom user control(.ascx) and then use your code to load in share point as web parts? coz I'm using forms authentication and i want to create user within the share point pages. is it possible? if not kindly give me an idea how to do it. it will be much appreciated. Confused
GeneralWorks Perfectly
Oslec
22:42 19 Apr '09  
Thank you very much Agusto..! Thumbs Up
GeneralHow to do step 6
huela
12:42 6 Feb '09  
I am new to webpart for sharepoint. I am successful with all the steps 1-5
but I don't understand how to do the step 6.
# Now you can utilize webpart and set the virtual path into your usercontrols and the simsalabim your webpart now load your usercontrol. You can create another usercontrol again and you can add your webpart again and set the usercontrols to load.
Could you help?
Thanks
GeneralError while importing .dwp file..
vimalthehero
2:20 1 Jan '09  
please help to find the solution for
Error:
one of the properties of the Web Part has an incorrect format. Windows SharePoint Services cannot deserialize the Web Part. Check the format of the properties and try again..


what should i do??

Thanks in advance..
GeneralError while adding the user control
jgeeetha
0:55 20 Nov '08  
1. I could able to register the WbpartLib successfully.
2. When i try to add the user control throws error as unexpected error
=> copied the ascx file and ascx.cs file to usercontrol folder under wss/80 folder
GeneralRe: Error while adding the user control
agusto xaverius
3:44 22 Nov '08  
Have you set the wss_minimal into Full
Generalreferenced dlls
seanrogers
8:44 30 Oct '08  
hi

thanks for the article/code. this has really helped me!

i do have one problem though:
my usercontrol.ascx references another dll (in which i have created a custom server control - "CustomWebServerControls.dll")

So when i try and load usercontrol.ascx into the webpart i get the error:
"Unknown server tag 'ABC:MyCustomTextBox'"

My question is: where should i put my CustomWebServerControls.dll?

I tried putting it in:
1.the GAC
2. in the C:\Inetpub\wwwroot\wss\VirtualDirectories\80\bin
3. registering it in the web.config of sharepoint

but i still get the error?

thanks for your help

sean
GeneralRe: referenced dlls
agusto xaverius
7:30 10 Nov '08  
if you used my code you don't have to register your assembly on web.config sharepoint. You just register my dll and than put your assembly on bin folder on your sharepoint site. If your sharepoint site is on port 80 so you put your assembly on that.

perhaps you can download my code dan that i have sample project too. you can test if my ascx is can be load on my webpart.

hope helpful Smile


Last Updated 12 Sep 2008 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010