Wednesday, October 20, 2010

Custom Content Query Web Part

When we need to add some custom property into OOB CQWP then we have to create custom CQWP.
As well as when we need redeploy CQWP then also we need to use custom content query web part.

Please view below code to create custom content query web part:-

1 point: We need to create a custom class whcih extend OOB content query web part class

public class CustomPortalContentQuery : ContentByQueryWebPart
{
public override ToolPart[] GetToolParts()
{
List toolPart = new List(base.GetToolParts());
toolPart.Insert(0, new CustomPortalToolPart());
return toolPart.ToArray();
}
protected override void OnInit(EventArgs e)
{
FixListGuid(); // this to fix list guid if you are redeploying cqwp to other site
this.ItemXslLink = this.ServerRelativeItemXslLink;
this.MainXslLink = this.ServerRelativeMainXslLink;
base.OnInit(e);

}
protected override void CreateChildControls()
{
base.CreateChildControls();
}

private void FixListGuid(){
try
{
if (!string.IsNullOrEmpty(base.WebUrl) && !string.IsNullOrEmpty(base.ListName))
{
using (SPWeb web = SPContext.Current.Site.OpenWeb(base.WebUrl, true))
{base.ListGuid = web.Lists[base.ListName].ID.ToString();
}
}
}
catch (Exception ex){}
}
}
}

2 point: We need to create a custom class for tool pane.
internal class CountryPortalToolPart : Microsoft.SharePoint.WebPartPages.ToolPart
{
CustomPortalContentQuery webpart;
TextBox itemXslLink;
Panel toolPanel;
Table toolPanelTable;
public CountryPortalToolPart()
{
this.Title = "Custom Settings";
}
protected override void CreateChildControls()
{
webpart = this.WebPartToEdit as CustomPortalContentQuery;
toolPanel = new Panel();toolPanel.CssClass = "ms-ToolPartSpacing";
toolPanel.Controls.Add(GetToolPanel());
this.Controls.Add(toolPanel);
base.CreateChildControls();
}

public override void ApplyChanges()
{try
{
webpart.ItemXslLink = itemXslLink.Text;
}

catch { }

base.ApplyChanges();}
private Control GetToolPanel()
{
toolPanelTable = new Table();
toolPanelTable.CellPadding = 0;
toolPanelTable.CellSpacing = 0;
toolPanelTable.Style["border-collapse"] = "collapse";
toolPanelTable.Attributes.Add("width", "100%");
toolPanelTable.Rows.Add(GetItemXslLinkRow());
return toolPanelTable;
}

private TableRow GetItemXslLinkRow()
{

TableRow row = new TableRow();
TableCell cell = new TableCell();

cell.Controls.Add(new LiteralControl("
Item XSL Link:
"));
cell.Controls.Add(new LiteralControl("
"));


itemXslLink = new TextBox();
if (string.IsNullOrEmpty(webpart.ItemXslLink))
{
itemXslLink.Text = this.webpart.ServerRelativeItemXslLink;
}
else
itemXslLink.Text = this.webpart.ItemXslLink;
cell.Controls.Add(itemXslLink);
cell.Controls.Add(new LiteralControl("
"));
row.Cells.Add(cell);
return row;
}
}


Hope it helps you.

Thanks!
Aviansh

No comments: