Module 3 - Code Snippets: Building Blocks for Web Part Development in SharePoint 2010

The following code shows how to use the ListViewByQuery control in a Web Part.
Note: The code also includes a CAML query statement that is used by an SPQuery object to set the items to be displayed in the ListViewByQuery control.

protected override void CreateChildControls()
{
SPWeb thisWeb = SPContext.Current.Web;
SPList tasks = thisWeb.Lists["Tasks"];
ListViewByQuery listTasks = new ListViewByQuery();
listTasks.List = tasks;
SPQuery taskQuery = new SPQuery(listTasks.List.DefaultView);
taskQuery.ViewFields = "<FieldRef Name='Title' /><FieldRef Name='Due' />";
taskQuery.Query = "<Where><Leq><FieldRef Name='Due' /><Value Type='DateTime'>"
+ SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now.AddMonths(1))
+ "</Value></Leq></Where>";
listTasks.Query = taskQuery;
this.Controls.Add(listTasks);
base.CreateChildControls();
}

 

The following code shows how to extract the selected people in a PeopleEditor control.
Note: The code runs in a Visual Web Part, and relies on there being a PeopleEditor control named peoplePicker, and an ASP.NET ListBox control called selectedPeople

namespace SharePointControls.ControlExample
{
public partial class ControlExampleUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void getPeople(object sender, EventArgs e)
{
string allPeople = peoplePicker.CommaSeparatedAccounts;
string[] selected = allPeople.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
foreach (string p in selected)
{
selectedPeople.Items.Add(p);
}
}
}
}

 

The following code shows how to use the SPGridView control in a Web Part to display list items from a list:

protected override void CreateChildControls()
{
SPGridView taskGrid = new SPGridView();
taskGrid.AutoGenerateColumns = false;
BoundField taskTitle = new BoundField();
taskTitle.DataField = "Title";
taskTitle.HeaderText = "To Do...";
taskGrid.Columns.Add(taskTitle);
SPWeb thisWeb = SPControl.GetContextWeb(Context);
SPList taskList = thisWeb.Lists["Tasks"];
SPDataSource listSource = new SPDataSource();
listSource.List = taskList;
SPDataSourceView view = listSource.GetView();
taskGrid.DataSource = listSource;
if (view.CanSort)
{
taskGrid.AllowSorting = true;
}
taskGrid.DataBind();
Controls.Add(taskGrid);
base.CreateChildControls();
}