Once I have an instance of an object "System.Web.UI.WebControls.WebParts.WebPart", How can I add it into a _layout page created in VisualStudio. I have tried with
ContentPlaceHolder ContentPlaceHolder = (ContentPlaceHolder)this.Master.FindControl("PlaceHolderMain");
ContentPlaceHolder.Controls.Add(myWebPart);
but it does not work.
UPDATE
I have different users in my site. On my application page (/_layout/ page) y get some information from their ActiveDirectory and I use that information to show different contents. Then I have a SQL table that I display using SharePoint Designer datasources. After that I create an application page on which I insert the datasource as a webpart (on the code it is inserted as ). On each row of that webpart I add an extra column with an hypelink that depends on that row ({@Id}). So I need to use that webpart created on SharePointDesigner on my application page, and then filter dinamically based on the user information. Otherwise I will need to create a sitepage for each of the possible filters (but I don't find a good solution to don't reuse the webpart).
Then I thought, let's go in the code and look for that webpart that I have created. once I find it, get it and show it on my application page. I use the next code to find the webpart:
System.Web.UI.WebControls.WebParts.WebPart personalwp = null;
List<string> lstpages = new List<string>();
SPSite site2 = SPContext.Current.Site;
SPWeb web2 = site2.OpenWeb();
SPList listpages = web2.Lists["Site Pages"];
SPListItemCollection pages = listpages.Items;
foreach (SPListItem page in pages)
{
lstpages.Add("\n" + page.DisplayName + " \n");
SPFile file = page.File;
using (SPLimitedWebPartManager mgr = file.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
try
{
SPLimitedWebPartCollection webparts = mgr.WebParts;
foreach (System.Web.UI.WebControls.WebParts.WebPart wp in webparts)
{
lstpages.Add(" - " + wp.Title + " ; ");
if (wp.Title == "Pending Evaluations")
{
personalwp = wp;
}
}
}
finally
{
// Needs to be disposed
//mgr.Web.Dispose();
}
}
}
Once I have the webpart on my object 'personalwp'I try to add it with:
ContentPlaceHolder ContentPlaceHolder = (ContentPlaceHolder)this.Master.FindControl("PlaceHolderMain");
ContentPlaceHolder.Controls.Add(myWebPart);
@Alexander: I don't think I can use the code taht you propose in the your first link on a dynamic way right?
To add the web part just add it directly in MarkUp by registering the tag: <%@ Register TagPrefix="ABC" Namespace="Namespace" Assembly="Assembly" %> and directly adding the web part, <ABC:ClassName ID="ControlID" FrameType="None" runat="server" __WebPartId="YouWebPartGUID" WebPart="true" />
Other possibility would be to add DataFormWebPart Directly on the code and set the filter programatically, but I couldn't find the way neither.
I already use on my site ListViewByQuery for other informations but with the same logic (filter values depending the user) and it works just so easily.
Any other ideas? Thanks
