Friday, September 12, 2008

Use User Control in Web Part (Deploy by STSDEV)

  1. Open STSDEV to create a new project with web part template as snapshot.


  2. Add a User Control in Project.

  3. Create directory structure in project as snapshot.


  4. Change the CustomWebPart1.cs file as following snippet.


    using System;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    namespace UCWebPartSl
    {
    public class CustomWebPart1 : WebPart
    {
    UserControl userControl;
    protected override void CreateChildControls()
    {
    //Label lblHello = new Label();
    //lblHello.Text = "Hello";
    //Controls.Add(lblHello);
    base.CreateChildControls();
    userControl =(UserControl)Page.LoadControl(@"/_controltemplates/WebUCOne.ascx");
    this.Controls.Add(userControl);
    }
    protected override void Render(HtmlTextWriter writer)
    {
    //base.Render(writer);
    userControl.RenderControl(writer);
    }
    }
    }


  5. Change the "Inherits" in WebUCOne.ascx file as following snippet. This assembly can be fetch by Reflector tool.
  6. Build on "DebugDeploy" mode.
  7. Activate the web part feature in Site Collection Features management page.
  8. Add web part to any page as snapshot.


    6 comments:

    Anonymous said...

    Hi! I'm new at sharepoint and stsdev. I've tried the steps you mentioned and I can successfully activate the feature and see CustomWebPart2 working, but the CustomWebPart1 doesn't work.
    I noticed that the ascx doesn't get copied to CONTROLTEMPLATES directory after debugDeploy.
    Shouldn't the ascx be inside rootFiles dir?

    Can you help?
    Thanks,

    Teddy Yu said...

    The ascx file should be put in rootfiles\TEMPLATE\CONTROLTEMPLATES. You can create the folder first and then drag the file in.

    wendy said...

    Hi, I can't see the snippet in step 5, what should I put on the Inherits of WebUCOne.ascx?

    wendy said...

    Hi, I can't see the snippet in step 5, what should I put on the Inherits of WebUCOne.ascx?

    Teddy Yu said...

    Hi Wendy,
    Sorry for reply this message a little later. I update the snapshot as you asked. Please let me know if you still have question.

    Unknown said...

    Hi,The type of Web Design Cochin is done with a more advanced web page design program and requires quite a bit of experience.Thanks.....