The way we add custom WebPart to a SharePoint page is by adding <AllUsersWebPart> element with WebPart’s exported xml populated inside <File> element. I will NOT discuss it further in here.
As you would have known, List View WebPart could NOT be exported in SharePoint page. Therefore, the question is How could we add the List View WebPart into SharePoint page?
I did it in managed code when Feature Activated feature receiver.
public
override
void
FeatureActivated(SPFeatureReceiverProperties properties)
{
try
{
SPWeb web = properties.Feature.Parent
as
SPWeb;
// Add webparts into MyView.aspx page
SPFile myviewFile = web.GetFile(
"Pages/myview.aspx"
);
AddListViewWebPart(myviewFile, web.Lists[
"ListName"
],
"Top"
, 1, web.Lists[
"ListName"
].Views[
"ViewName"
].ID);
}
catch
(Exception ex)
{
// Your Error handling here ...
}
}
private
void
AddListViewWebPart(SPFile file, SPList list,
string
webPartZone,
int
webPartOrder, Guid viewId)
{
SPLimitedWebPartManager limitedWebPartManager = file.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
XsltListViewWebPart wp =
null
;
list.ParentWeb.AllowUnsafeUpdates =
true
;
try
{
// create an instance of the ListViewWebPart
wp =
new
XsltListViewWebPart();
// convert the list GUID to a string, must include braces (ToString("B")) and be in uppers (ToUpper())
wp.ListName = list.ID.ToString(
"B"
).ToUpper();
// optionally set the title of the web part
wp.Title = list.Title;
wp.ViewGuid = viewId.ToString(
"B"
).ToUpper();
wp.ChromeType = System.Web.UI.WebControls.WebParts.PartChromeType.None;
// add the web part to the limited web part manager.
limitedWebPartManager.AddWebPart(wp, webPartZone, webPartOrder);
// you need to update the list because a view was just added to it
list.Update();
}
finally
{
// do some fun cleanup of disposable items.
if
(limitedWebPartManager !=
null
)
{
if
(limitedWebPartManager.Web !=
null
)
{
limitedWebPartManager.Web.Dispose();
}
limitedWebPartManager.Dispose();
}
if
(wp !=
null
)
{
wp.Dispose();
}
list.ParentWeb.AllowUnsafeUpdates =
true
;
}
}
No comments:
Post a Comment