Monday 11 March 2013

Programmatically Display List data in Web part getting List Name & filed Name from Edit Web Part Properties Drop Down in SharePoint 2010

To display the list data in a web part, open Visual Studio 2010 & create a Web Part Solution. The Web Part solution will appear as shown below




Now in the above solution add a class file which will contain the code to create a dropdown in the Edit Web Part Properties. 
I will declare this class file to work as a tool part as shown below

class DisplayListToolPart : Microsoft.SharePoint.WebPartPages.ToolPart

In this class file I will write the following code


class DisplayListToolPart : Microsoft.SharePoint.WebPartPages.ToolPart
{
#region Controls Declaration
Panel toolPartPanel;
DropDownList ddlAllLists;
DropDownList ddlAllListFields;
TextBox txtItemCount;
#endregion
protected override void CreateChildControls()
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb web = site.OpenWeb())
{
#region Creating instances of Toolpart Controls
//Add Panel
toolPartPanel = new Panel();
toolPartPanel.GroupingText = "<b>List Display Configuration</b>";
//Add List Drop Down
ddlAllLists = new DropDownList();
ddlAllLists.Width = Unit.Pixel(200);
//Add List Item Fields Drop Down
ddlAllListFields = new DropDownList();
ddlAllListFields.Width = Unit.Pixel(200);
//Add List Item Count Text Box
txtItemCount = new TextBox();
txtItemCount.Width = Unit.Pixel(200);
ddlAllLists = new DropDownList();
ddlAllLists.ID = "ddlAllLists";
ddlAllLists.AutoPostBack = true;
ddlAllLists.Width = Unit.Pixel(200);
//Function to Add All List Fields in ddlAllListFields dropdown on selected item changed
ddlAllLists.SelectedIndexChanged += new EventHandler(ddlAllLists_SelectedIndexChanged);
#endregion
//Function to add All Lists in the ddlAllLists dropdown
populateToolPartControls();
#region Adding all control to toolpart stack
toolPartPanel.Controls.Add(new LiteralControl("Select List Name"));
toolPartPanel.Controls.Add(new LiteralControl("</br>"));
toolPartPanel.Controls.Add(ddlAllLists);
toolPartPanel.Controls.Add(new LiteralControl("Select  List Item To Display"));
toolPartPanel.Controls.Add(new LiteralControl("</br>"));
toolPartPanel.Controls.Add(ddlAllListFields);
toolPartPanel.Controls.Add(new LiteralControl("Select Number of Items to Display"));
toolPartPanel.Controls.Add(new LiteralControl("</br>"));
toolPartPanel.Controls.Add(txtItemCount);
//Add Panel Control to Edit Web Part Properties
Controls.Add(toolPartPanel);
base.CreateChildControls();
#endregion
}
}
});
}
catch (Exception ex)
{
//Log
}
}
//Function to add all lists from the current Site
public void populateToolPartControls()
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb web = site.OpenWeb())
{
ddlAllLists.Items.Clear();
//Fetch all Lists & Display in ddlAllLists Dropdown
foreach (SPList list in web.Lists)
{
ddlAllLists.Items.Add(new ListItem(list.Title));
}
ddlAllLists.Items.Insert(0, "--Select--");
}
}
});
}
catch (Exception ex)
{
//Log
}
}
void ddlAllLists_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
populateAllListItemsControl();
}
catch (Exception ex)
{
//Log
}
}
//Function to add all list items of the Selected List
public void populateAllListItemsControl()
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb web = site.OpenWeb())
{
//Get Selected List
SPList lstList = web.Lists[ddlAllLists.SelectedItem.Text];
ddlAllListFields.Items.Clear();
foreach (SPField field in lstList.Fields)
{
//Populate list Columns Dropdown
ddlAllListFields.Items.Add(new ListItem(field.Title, field.InternalName));
}
}
}
});
}
catch (Exception ex)
{
//Log
}
}
//Function to send the selected values to the web part class file.
public override void ApplyChanges()
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//Create object of web part class file
ListDisplayWebPart.ListDisplayWebPart eventList = (ListDisplayWebPart.ListDisplayWebPart)this.ParentToolPane.SelectedWebPart;
eventList.listName = ddlAllLists.SelectedItem.Text;
eventList.fieldName = ddlAllListFields.SelectedValue;
eventList.numberofItems = txtItemCount.Text;
});
}
catch (Exception ex)
{
//Log
}
}
}


Now in the web part class file I will first declare the class to work as a web part as shown below

public class ListDisplayWebPart : Microsoft.SharePoint.WebPartPages.WebPart

Now declare the controls to load in the web part & to get the values from the tool part class file.


public string listName { get; set; }
public string fieldName { get; set; }
public string numberofItems { get; set; }


Also to add custom properties to the tool part I will create a new instance of the tool part class file as shown below

//Function to fetch values from Edit Web Part Properties i.e from ToolPart
public override ToolPart[] GetToolParts()
{
ToolPart[] allToolParts = new ToolPart[3];
WebPartToolPart standardToolParts = new WebPartToolPart();
CustomPropertyToolPart customToolParts = new CustomPropertyToolPart();
allToolParts[0] = standardToolParts;
allToolParts[1] = customToolParts;
allToolParts[2] = new DisplayListToolPart();
return allToolParts;
}


Now I will create controls

private Label instructionsLabel;
private Label listNameLabel;
private Label listItemsLabel;


Below is the code in the web part class file


public class ListDisplayWebPart : Microsoft.SharePoint.WebPartPages.WebPart
{
#region get controls to load
public string listName { get; set; }
public string fieldName { get; set; }
public string numberofItems { get; set; }
#endregion

//Function to fetch values from Edit Web Part Properties i.e from ToolPart
public override ToolPart[] GetToolParts()
{
ToolPart[] allToolParts = new ToolPart[3];
WebPartToolPart standardToolParts = new WebPartToolPart();
CustomPropertyToolPart customToolParts = new CustomPropertyToolPart();

allToolParts[0] = standardToolParts;
allToolParts[1] = customToolParts;
allToolParts[2] = new DisplayListToolPart();
return allToolParts;
}
//Controls
private Label instructionsLabel;
private Label listNameLabel;
private Label listItemsLabel;

protected override void CreateChildControls()
{
try
{
//Create the Instructions label
instructionsLabel = new Label();
instructionsLabel.Text = "Edit this Web Part to select the list to display";
//Create the List Contents label
listNameLabel = new Label();
//Create the label that displays the items
listItemsLabel = new Label();

if (listName != String.Empty && listName != null)
{
if (listName == "--Select--")
{
listNameLabel.Text = "Please Select List";
listNameLabel.ForeColor = System.Drawing.Color.Red;
}
else
{
listNameLabel.Text = "ListName: " + listName;
listNameLabel.ForeColor = System.Drawing.Color.Blue;
instructionsLabel.Text = "";
listItemsLabel.Text = fillListLabel(listName, fieldName, numberofItems);
}
}
else
{
listNameLabel.Text = "";
}

listNameLabel.Font.Bold = true;
listNameLabel.Font.Size = 11;

this.Controls.Add(instructionsLabel);
this.Controls.Add(listNameLabel);
this.Controls.Add(listItemsLabel);
}
catch (Exception ex)
{
//Log
}
}

protected override void Render(HtmlTextWriter writer)
{
try
{
instructionsLabel.RenderControl(writer);
writer.Write("<br /><br />");
listNameLabel.RenderControl(writer);
writer.Write("<br /><br />");
listItemsLabel.RenderControl(writer);
}
catch (Exception ex)
{
//Log
}
}

//Get the Items from the selected list
private string fillListLabel(string listname, string fieldname, string numberofitems)
{
string labelHTML = String.Empty;
int itemcount = 0;
try
{
itemcount = Convert.ToInt32(numberofitems);
using (SPWeb currentWeb = SPContext.Current.Web)
{
SPList list = currentWeb.Lists[listname];
if (list != null)
{
//Show total items
labelHTML += "<b>Total Items: " + list.Items.Count + "</b><br /><br />";

//I want to display names of selected field of selected number of items.
int i = 0;
foreach (SPListItem item in list.Items)
{
if (i < itemcount)
{
labelHTML += item[fieldname] + "<br /><br />";
i++;
}
else
{
break;
}
}
}
}
}
catch (Exception ex)
{
labelHTML = "<span style='color:red;'>Please Enter a valid Number to display List Items </b><br />" + ex.Message + "</span>";
}
return labelHTML;
}
}


Build & deploy the solution. In the Web Part Properties of this web part I will get all the Lists of that site in the drop down. After selecting specific list name the event is fired & all the respective field names are populated in the other drop down. We can select the field name from this drop down which we want to display in the web part.

No comments:

Post a Comment