Programmatically adding webparts to the webpart manager

Last post 07-08-2008 9:32 AM by OutOnFarm. 9 replies.

Sort Posts:

  • Programmatically adding webparts to the webpart manager

    01-19-2005, 7:17 AM
    • Member
      80 point Member
    • sirosoft
    • Member since 05-02-2003, 7:43 AM
    • Posts 18
    I am trying to add a webpart to a webpartzone programmatically.

    My webpart is a user control(.ascx) file with ID "Event"
    My webpartZone is ID "Zone1"

    I am trying to use webpartmanager.addwebpart(Event,Zone1,0) to add the webpart to Zone1

    Value of type 'EventsCalendar_ascx' cannot be converted to 'System.Web.UI.WebControls.WebParts.WebPart'.

    My preference is to write my webparts as user controls(.ascx) as opposed to custom controls(.vb) yet it does not appear that I can then programmatically add a webpart to a zone.

    I understand that I could use the CatalogZone with the Page and Declataritive zones to facilitate the process but I cannot find away to customize the template for these controls. If there is a way to customize the functionality and look of these controls I could use that instead.

    Please help.

    Thanks
  • Re: Programmatically adding webparts to the webpart manager

    01-19-2005, 8:01 AM
    • All-Star
      29,644 point All-Star
    • Fredrik N
    • Member since 06-22-2002, 5:03 AM
    • Sweden
    • Posts 5,334
    You hva to turn your user control into a Generic WebPart, you can do that by using the WebPartManager's CreateWebPart method:

    GenericWebPart gw = MyWebPartManager.CreateWebPart(LoadContorl("myUserContorl.ascx"));

    MyWebPartManager.AddWebPart(gw, MyWebPartZone, 0);
    /Fredrik Normén - fredrikn @ twitter

    ASPInsider

    Microsoft MVP, MCSD, MCAD, MCT

    ASPInsiders
    My Blog
  • Re: Programmatically adding webparts to the webpart manager

    01-21-2005, 8:41 AM
    • Member
      80 point Member
    • sirosoft
    • Member since 05-02-2003, 7:43 AM
    • Posts 18
    I now get an error

    The specified control of type 'EventsCalendar_ascx' does not have an ID.

    Description: An unhandled exception occurred during the execution of the current web Request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.ArgumentException: The specified control of type 'EventsCalendar_ascx' does not have an ID.

    Source Error:


    Line 21: Private Sub DP_Controls_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DP_Controls.SelectedIndexChanged
    Line 22: Dim gw As System.Web.UI.WebControls.WebParts.GenericWebPart
    Line 23: gw = WPM_Home.CreateWebPart(LoadControl("webparts\EventsCalendar.ascx"))
    Line 24: gw.ID = "EventsCalendar1"
    Line 25: WPM_Home.AddWebPart(gw, WP_Panel1, 0)

    How do I set the Id for the control.

    I tried gw.ID = "String"

    Thanks
  • Re: Programmatically adding webparts to the webpart manager

    01-21-2005, 9:13 AM
    • All-Star
      29,644 point All-Star
    • Fredrik N
    • Member since 06-22-2002, 5:03 AM
    • Sweden
    • Posts 5,334
    You must set the ID to your user control:

    Control control = LoadControl("webparts\EventsCalendar.ascx")
    control.ID = "EventsCalendar1"
    gw = WPM_Home.CreateWebPart(control)
    /Fredrik Normén - fredrikn @ twitter

    ASPInsider

    Microsoft MVP, MCSD, MCAD, MCT

    ASPInsiders
    My Blog
  • Re: Programmatically adding webparts to the webpart manager

    01-24-2005, 7:14 AM
    • Member
      655 point Member
    • kaanoezturk
    • Member since 10-30-2003, 3:48 AM
    • Posts 140
    Hi,

    I try to do the same with my custom webcontrols.

    I have problem with the custom properties of my controls. When I create a GenericWebPart of my control and add it to a WebPartZone, then the control loses it's all properties that are set before. I cannot access them anymore. What is the best solution for using custom controls as webParts?

    BaseControl control = BaseControl.CreateControl(...); // it is the base class for my controls
    control.ID = "myControl";
    control.ControlConfiguration = controlConfig;

    GenericWebPart gwp = wpManager.CreateWebPart(control); // after this point, the properties of the control aren't accessible anymore
    wpm.AddWebPart(gwp, wpZone, 0);

    KaaN
  • Re: Programmatically adding webparts to the webpart manager

    01-24-2005, 7:18 AM
    • All-Star
      29,644 point All-Star
    • Fredrik N
    • Member since 06-22-2002, 5:03 AM
    • Sweden
    • Posts 5,334
    You can access it if you use the GenericWebParts's ChildControl Property, and cast the returned control to your user control.

    You can also create your own custom control and inherits the WebPart class, if you do so, you don't need to "turn" the control into a Generic webpart.
    /Fredrik Normén - fredrikn @ twitter

    ASPInsider

    Microsoft MVP, MCSD, MCAD, MCT

    ASPInsiders
    My Blog
  • Re: Programmatically adding webparts to the webpart manager

    01-24-2005, 8:08 AM
    • Member
      655 point Member
    • kaanoezturk
    • Member since 10-30-2003, 3:48 AM
    • Posts 140
    This is Default.aspx wit 1 manager and 1 zone:


    <%@ Page Trace="true" Language="C#" CodeFile="Default.aspx.cs" Inherits="Default_aspx" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
    <title>Untitled Page</title>
    </head>
    <body>
    <form id="form1" runat="server">
    <asp:WebPartManager ID="WebPartManager1" runat="server">
    </asp:WebPartManager>
    <asp:WebPartZone ID="WebPartZone1" runat="server">
    </asp:WebPartZone>
    </form>
    </body>
    </html>


    This is the code file: In init() I create a WebPart.


    public partial class Default_aspx : System.Web.UI.Page
    {
    public Default_aspx()
    {
    Load += new EventHandler(Page_Load);
    }

    void Page_Load(object sender, EventArgs e)
    {
    }

    protected override void OnInit(EventArgs e)
    {
    if (WebPartZone1.WebParts.Count == 0)
    {
    MyWebPart control = new MyWebPart();
    control.MyValue = "kaan";
    control.ID = "id";
    control.Title = "kaan";

    WebPartManager1.AddWebPart(control, WebPartZone1, 0);
    }
    }
    }


    and this is the webpart:


    public class MyWebPart : WebPart
    {
    private string _myValue;

    public string MyValue
    {
    get
    {
    return this._myValue;
    }
    set
    {
    this._myValue = value;
    }
    }

    protected override void OnUnload(EventArgs e)
    {
    Context.Response.Write(this.MyValue);
    }

    protected override void Render(HtmlTextWriter writer)
    {
    writer.Write("dfgsdfgsdfgdfgsdfg");
    }
    }

    If I run this code, I find 3 WebParts on the page. Although I set the MyValue in Default.aspx.cs, in OnUnLoad() it is empty!!

    KaaN

  • Re: Programmatically adding webparts to the webpart manager

    01-24-2005, 10:27 AM
    • Member
      655 point Member
    • kaanoezturk
    • Member since 10-30-2003, 3:48 AM
    • Posts 140
    I am adding a webpart in init() event of the page. why adds the page on every postback a webpart to the page? When I restart the IIS, the webparts resist. Where is the information saved, that the page has 4 or 5 webparts?

    I think, the webparts framework of asp.net has very strange behaviour. You can not simply add a custom control into a webpart or convert it.

    My code runs when I inherit webpart for my controls and add it to the page with "this.Controls.Add()". But my code doesn't run when I create the controls in Webpartzone's with "webpartmanager.addwebpart()". in the second case, all properties of my controls get null.

    KaaN
  • Re: Programmatically adding webparts to the webpart manager

    01-24-2005, 10:48 AM
    • All-Star
      29,644 point All-Star
    • Fredrik N
    • Member since 06-22-2002, 5:03 AM
    • Sweden
    • Posts 5,334
    The WebPart feature use a personalization feature that will save the WebParts and its settings into a data source based on the provider you use. So if you don't turn off the Personalization for the current page, the WebPart you have added will be saved and automatically added to the page next time you visit it. This could be done on a user level (if the user is authenticated) or for everyone if the mode of the WebPart feateurs is in a shared scope.

    I should recommend you to read my post on my blog about creating a WebPart. Hopefully it will give your some more information.
    /Fredrik Normén - fredrikn @ twitter

    ASPInsider

    Microsoft MVP, MCSD, MCAD, MCT

    ASPInsiders
    My Blog
  • Re: Programmatically adding webparts to the webpart manager

    07-08-2008, 9:32 AM
    • Member
      10 point Member
    • OutOnFarm
    • Member since 05-09-2008, 2:55 PM
    • Posts 6

    Kaan, I also encountered the issue of having multiple web parts when adding user control programmatically. For my application, we want controls to appear for some users and not for others. I thought programmatically adding controls was the way but abandoned the effort. Instead, I'm now using roles so the WebPartManager turns on and off the visibility of the control.

     Within this thread, there is a link to Fredrik Normen's Blog. He has a post (http://fredrik.nsquared2.com/viewpost.aspx?PostID=90) that describes "Show/Hide Web Parts based on Role". I used this as a base, but instead of building a custom WebPartManager, I added the property  OnAuthorizeWebPart="AuthorizingWebParts" to my WebPartManager. In the code-behind (C#), I have the protected method:

    protected void AuthorizingWebParts(object sender, WebPartAuthorizationEventArgs e)
            {
                if (!String.IsNullOrEmpty(e.AuthorizationFilter))
                {
                    //Advisor
                    if (e.AuthorizationFilter.Equals("AdvisorRole"))
                    {
                        if (!currentSession.EntitledToAdvisor) {
                            e.IsAuthorized = false;
                        } else {
                            e.IsAuthorized = true;
                        }
                    }

    }

    Some of this is specific to my application where currentSession is a custom object that I have  instantiated with user information. The EntitledToAdvisor returns a boolean.
     

Page 1 of 1 (10 items)