Custom Picker in Sharepoint
By Anatoly Mironov
PeopleEditor is a nice webcontrol for picking people. To add it to your webpart or page is easy: But there is more we can do with pickers in Sharepoin. We can define our own pickers. Jeremy Luerkens gives one such example and a code sample (!). Another example can be found in Sharepoint as a Development Platform (p. 661), even though it misses the important class BookQueryControl. Just to start I made a book picker (I simplified and changed the idea provided in the book). Here is the working result, for simplicity the whole code is in one file: [sourcecode language=“csharp”] public partial class WPBookPickerUserControl : UserControl { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { pnlBook.Controls.Add(new BookEditor() { Width = Unit.Pixel(200), MultiSelect = false}); } } } public class Book { public string Title { get; set; } public string Author { get; set; } public string Price { get; set; } public string Publisher { get; set; } } public class BookDataManager { private static Book[] _books = { new Book {Title = “SP”, Author = “John”, Price = “2€”, Publisher = “Amazon”}, new Book {Title = “JS”, Author = “David”, Price = “3€”, Publisher = “Amazon”} }; private static DataTable GetDataTable(IEnumerable books) { var table = new DataTable(); table.Columns.Add(“Title”, typeof(string)); table.Columns.Add(“Author”, typeof(string)); table.Columns.Add(“Price”, typeof(string)); table.Columns.Add(“Publisher”, typeof(string)); foreach (var b in books) { table.LoadDataRow(new string[] { b.Title, b.Author, b.Price, b.Publisher }, true); } return table; } public static DataTable ValidateBook(string key) { var books = _books.Where(c => c.Title == key).ToArray(); return GetDataTable(books); } public static DataTable SearchForBooks(string keyword) { var books = _books.Where(c => c.Title.Contains(keyword)).ToArray(); return GetDataTable(books); } public static PickerEntity ConvertFromDataRow(DataRow dr, PickerEntity pi) { pi = pi ?? new PickerEntity(); var t = dr[“Title”].ToString(); var a = dr[“Author”].ToString(); var p = dr[“Price”].ToString(); var l = dr[“Publisher”].ToString(); pi.Key = t; pi.DisplayText = string.Format("{0} ({1}), {2}", t, a, p); pi.EntityData = new Hashtable(); foreach(DataColumn col in dr.Table.Columns) { pi.EntityData[col.ColumnName] = dr[col.ColumnName]; } return pi; } } public class BookEditor : EntityEditorWithPicker { public BookEditor() { PickerDialogType = typeof (BookPickerDialog); ValidatorEnabled = true; } public override PickerEntity ValidateEntity(PickerEntity needsValidation) { var tblItem = BookDataManager.ValidateBook(needsValidation.Key); needsValidation.IsResolved = false; if (tblItem != null && tblItem.Rows.Count > 0) { needsValidation = BookDataManager.ConvertFromDataRow(tblItem.Rows[0], needsValidation); needsValidation.IsResolved = true; } return needsValidation; } } public class BookQueryControl : PickerQueryControlBase { public TableResultControl ResultControl { get { return (TableResultControl)base.PickerDialog.ResultControl; } } public BookEditor EditorControl { get { return (BookEditor)base.PickerDialog.EditorControl; } } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); base.ColumnList.Visible = false; } private DataTable CreateDataTable() { // Method variables DataColumn column; // Init data table DataTable table = new DataTable(); table.Locale = CultureInfo.InvariantCulture; // Loop visible column names foreach (string columnName in ResultControl.ColumnNames) { column = new DataColumn {DataType = typeof (string), ColumnName = columnName}; table.Columns.Add(column); } // Return table return table; } public override PickerEntity GetEntity(DataRow dr) { // No datarow provided if (dr == null) return null; var pi = new PickerEntity(); var t = dr[“Title”].ToString(); var a = dr[“Author”].ToString(); var p = dr[“Price”].ToString(); var l = dr[“Publisher”].ToString(); pi.Key = t; pi.DisplayText = string.Format("{0} ({1}), {2}", t, a, p); pi.IsResolved = true; pi.EntityData = new Hashtable(); foreach (DataColumn col in dr.Table.Columns) { pi.EntityData[col.ColumnName] = dr[col.ColumnName]; } return pi; } protected override int IssueQuery(string search, string group, int pageIndex, int pageSize) { search = (search != null) ? search.Trim() : null; if (string.IsNullOrEmpty(search)) { PickerDialog.ErrorMessage = “No search provided”; return 0; } var table = BookDataManager.SearchForBooks(search); if (table == null || table.Rows.Count == 0) { PickerDialog.ErrorMessage = “No matching books found.”; return 0; } PickerDialog.Results = table; PickerDialog.ResultControl.PageSize = table.Rows.Count; return table.Rows.Count; } } public class BookPickerDialog : PickerDialog { public BookPickerDialog() : base(new BookQueryControl(), new TableResultControl(), new BookEditor()) { DialogTitle = “Custom Book Picker Dialog”; Description = “Please select one or more books”; MultiSelect = false; } protected override void OnPreRender(EventArgs e) { var resultControl = (TableResultControl) ResultControl; var columnDisplayNames = resultControl.ColumnDisplayNames; var columnNames = resultControl.ColumnNames; var columnWidths = resultControl.ColumnWidths; columnDisplayNames.Clear(); columnNames.Clear(); columnWidths.Clear(); var cols = new string[] {“Title”, “Author”, “Price”, “Publisher”}; columnDisplayNames.AddRange(cols); columnNames.AddRange(cols); columnWidths.AddRange(new string[] { “40%”, “20%”, “10%”, “30%”}); base.OnPreRender(e); } } [/sourcecode] Of course the best way is to create separate files for each class, but don’t forget to add Safecontrol to web.config.
<SafeControl
Assembly="Contoso, Version=1.0.0.0, Culture=neutral, PublicKeyToken=20c0327f8b01d979"
Namespace="Contoso.WebControls"
TypeName="\*" Safe="True" SafeAgainstScript="False" />
```Okay, but what if we need to override PeopleEditor so we have the functionality of the standard People Editor but we can decide which users can be chosen, more than just SPGroup, User or SecGroup. We can create a custom Editor which inherits from PeopleEditor. There ValidateEntity method must be overriden. One shortcomming in that approach is that the associated PeopleQueryControl is sealed and cannot be inherited. That means PickerDialog will still return all people. If you can live without PickerDialog, then you can just override ValidateEntity: \[sourcecode language="csharp"\] namespace Contoso.WebControls { public class CustomEditor : PeopleEditor { public override PickerEntity ValidateEntity(PickerEntity pi) { if (pi.Key.StartsWith("a", StringComparison.InvariantCultureIgnoreCase)) { pi.IsResolved = true; return base.ValidateEntity(pi); } pi.IsResolved = false; return pi; } } } \[/sourcecode\] In this dummy example we will only allow people whose name starts with A, just to provide an example... Than register the tagprefix:
<%@ Register TagPrefix=“Contoso” Namespace=“Contoso.WebControls” Assembly="$SharePoint.Project.AssemblyFullName$" %>
<Contoso:CustomEditor runat=“server” ID=“customEditor” MultiSelect=“false” Width=“200px” EnableBrowse=“false”/>
## Comments from Wordpress.com
####
[vishal]( "modi.vishal2489@gmail.com") - <time datetime="2012-08-09 08:01:03">Aug 4, 2012</time>
hi i want to hide some of the column like Account Name,Department from my custom people picker picker dialog box how it can be done, hear is my custom people picker code private PeopleEditor userSelect; PickerEntity pickerEntity; protected override void CreateChildControls() { userSelect = new PeopleEditor(); pickerEntity = new PickerEntity(); userSelect.MultiSelect = true; userSelect.AllowEmpty = false; userSelect.AutoPostBack = false; userSelect.PickerDialogToolTip = "Select the User to get Alerts"; userSelect.PlaceButtonsUnderEntityEditor = true; userSelect.ID = "PeopleEditor"; userSelect.MaximumEntities = 5; userSelect.SelectionSet = "User,SecGroup"; userSelect.Rows = 1; //To apply style to people picker LiteralControl styleControl = new LiteralControl(); styleControl.Text = " .ms-inputuserfield{ font-size:8pt; font-family:Verdana,sans-serif; border:1px solid #a5a5a5;} div.ms-inputuserfield a{color:#000000;text-decoration: none;font-weight:normal;font-style:normal;} div.ms-inputuserfield{padding-left:1px;padding-top:2px;} "; this.Controls.Add(styleControl); this.Controls.Add(userSelect); } thanx in advance
<hr />