Creating Custom web part by inheriting DataFormWebPart
Last week I was working on creating a custom web part based on xml/xslt my first thought went to use the features of DataFormWebPart so I decided to create a custom web part by inheriting the DataFormWebPart. I started googling for a nice article on the same but could not find any which talks about inheriting a DataFormWebPart provided with SharePoint 2010 that’s why I wanted to share this article with you all
first thing you would have to add the reference of Microsoft.SharePoint.WebPartPages Name space
using Microsoft.SharePoint.WebPartPages;
then inherit your web part with DataFormWebPart
[ToolboxItemAttribute(false)]
public class xslwp: DataFormWebPart
after this you would be required to override 2 methods
1st for applying the xslt
public override void DataBind()
2nd for creating datasource XPathNavigator in case if you miss this override xslt would be applied on xml with empty node value (SharePoint behavior since its list data is also provided in node attributes not in form of node values)
protected override XPathNavigator GetXPathNavigator(string viewPath)
that’s all you need for creating a webpart which is inheriting DataFormWebPart you can also overide other common methods like prerender or createchild controls if you need.
below is a sample code for the same
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
namespace testwebpart.xslwp
{
[ToolboxItemAttribute(false)]
public class xslwp: DataFormWebPart
{
XmlDocument doc;
public override void DataBind()
{
doc = GetFeedsXML(); //method to get xmldocument
XmlDataSource source = new XmlDataSource();
source.ID = "wallXML";
source.Data = doc.InnerXml;
this.DataSource = source;
base.Xsl = this.Xsl;
base.DataBind();
}
protected override XPathNavigator GetXPathNavigator(string viewPath)
{
return doc.CreateNavigator();
}
}
}
Comments
Post a Comment