Wednesday, August 11, 2010

Add Web Part programmatically using SPLimitedWebPartManager

Add Web Part programmatically

=========================================================================


public void AddWebPartToPage(string webPartFullName, SPWeb web, string zoneId, int zoneIndex)
{
SPFile file = null;
XmlUrlResolver xmlResolver = new XmlUrlResolver();
xmlResolver.Credentials = CredentialCache.DefaultCredentials;
FileStream fs = new FileStream(webPartFullName, FileMode.OpenOrCreate);
XmlReader reader = new XmlTextReader(fs);
string errorMsg;
SPLimitedWebPartManager manager = null;

try
{
file = web.GetFile(strPageUrl);
if (file.CheckOutStatus == SPFile.SPCheckOutStatus.None)
{
file.CheckOut();
manager = file.GetLimitedWebPartManager(PersonalizationScope.Shared);
System.Web.UI.WebControls.WebParts.WebPart tempWebPart = manager.ImportWebPart(reader, out errorMsg);
manager.AddWebPart(tempWebPart, zoneId, zoneIndex);
web.Update();
}
}
catch (Exception ex)
{
// write exception
}
finally
{
if (manager != null)
manager.Dispose();

if (file != null)
{
file.CheckIn("added web parts");
file.Publish("added web parts");
}
if (fs != null)
{
fs.Close();
fs.Dispose();
}

}
}
=========================================================================

this above function can be use for following points:-

Import WebPart programmatically using SPLimitedWebPartManager
or
Add Web Part programmatically using SPLimitedWebPartManager
or
Add Web Part to Page Programmatically

or

any exception comes like this:-
Throws this error on ImportWebPart..."The file you imported is not
valid. Verify that the file is a Web Part description file (*.webpart
or *.dwp) and that it contains well-formed XML."

then its issue with credential. please us CredentialCache.DefaultCredentials as mention in above function.

or

any exception comes like this:-
"Object reference not set to an instance of an object" while ImportWebPart
then its isse with loading file. Dont use File to load use FileStream as mentioned in above function.

or

SPLimitedWebPartManager.AddWebPart():



Thanks!
Avinash Dad

No comments: