SharePoint user controls
WSS 3.0 comes with a number of user controls that you can use in your web parts and application pages. These controls are located in the 12\TEMPLATE\CONTROLTEMPLATES folder.
SharePoint server controls
The Microsoft.SharePoint.WebControls namespace of the Microsoft.SharePoint.dll contains a number of SharePoint server controls that you can use in you web parts and application pages.
- DateTimeControl control
- InputFormTextBox control
- InputFormCheckBox, InputFormCheckBoxList and InputFormCheckBoxListValidator controls
- InputFormRadioButton control
- SharePoint validation controls
- PeopleEditor control
- ListFieldIterator control
- ListViewByQuery control
- WebApplicationSelector control
- SPGridView control (written by Paul Robinson)
- SPDataSource control (written by Chris O’Brien)
Other controls that are useful on application pages for the Central administration can be found in theMicrosoft.SharePoint.ApplicationPages.Administration.dll located in the 12\CONFIG\ADMINBIN directory:
- AdministrationDataSourceControl control
The Microsoft.SharePoint.WebControls namespace of the Microsoft.SharePoint.dllcontains a
number of validation controls that can be used on application pages and web
parts to validate user entry in the SharePoint controls.
Rich Text Box:
Register:
<%@ Register
Tagprefix="SharePoint"
Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint,
Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"
%>
Using:
<SharePoint:InputFormTextBox
TextMode="MultiLine" runat="server"
ID="rtct" RichTextMode="FullHtml"
RichText="true"></SharePoint:InputFormTextBox>
SPGridView
When you create ASP.NET applications, you often need to
display data in the format of rows and columns. Although you could create an
HTML table by using code, you become much more productive by using
server-side controls such as the GridView control introduced with Microsoft
ASP.NET 2.0. The Microsoft Windows SharePoint Services platform provides a grid control named SPGridView that inherits from the ASP.NET
GridView control. The SPGridView control provides a great
alternative for displaying tabular data in SharePoint-based solutions.
When you add the SPGridView control to a custom
application page, you must first add an @Register directive to the top of the
page to reference the Microsoft.SharePoint assembly and to import the
Microsoft.SharePoint.WebControls namespace.
<%@ Register
Tagprefix="SharePoint"
Namespace="Microsoft.SharePoint.WebControls"
Assembly="Microsoft.SharePoint,
[4-part assembly name] " %>
After you add the @Register directive, you can create a
control tag within an application page to instantiate the SPGridView control.
Notice that the control tag must use the Tagprefix attribute value that is
defined in the @Register directive.
<SharePoint:SPGridView
runat="server"
ID="grdPropertyValues"
AutoGenerateColumns="false"
RowStyle-BackColor="#DDDDDD"
AlternatingRowStyle-BackColor="#EEEEEE"
/>
Unlike other grid controls used in ASP.NET, the
SPGridView control does not support the automatic generation of columns. You
receive a run-time error unless you assign the AutoGenerateColumns attribute
a value of "false".
Populating the SPGridView Control with an ADO.NET
DataTable
One easy way to populate the SPGridView control is to
create an ADO.NET DataTable. That's because you can directly bind the
DefaultView property of a DataTable to the DataSource property of the
SPGridView control, and then call the DataBind method.
This example introduces a custom utility class named
PropertyCollectionBinder, which encapsulates the work of creating and
populating an ADO.NET DataTable object with two columns. It also provides a
convenience method named BindGrid, which accepts a parameter reference to
SPGridView control, and then populates it by data-binding the data within the
ADO.NET DataTable.
For More Detail:
Notes :
One advantage of using the SPGridView control in
SharePoint-based solutions is that it has been integrated with the cascading
style sheets that are built into Windows SharePoint Services 3.0. Also, the
SPGridView control is heavily used in standard application pages and Web
Parts that are built into Windows SharePoint Services. That means your custom
application pages and Web Parts constructed using the SPGridView control can
have the same look and feel as other aspects of the standard Windows
SharePoint Services user interface.
Remember that the SPGridView control does not support
the automatic generation of columns. That means you must explicitly bind each
column using SPBoundField as you just saw. However, it is not difficult to
supply the code you need to populate it with data. You can do this by
creating an ADO.NET DataTable or by using a query object that return an
ADO.NET DataTable object, such as an SPSiteDataQuery object.
People Picker
Assembly Refrence:
<%@ Register
Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls"
Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral,
PublicKeyToken=71e9bce111e9429c" %>
Control:
<SharePoint:PeopleEditor
ID="ProjectManager" AllowEmpty="false" ValidatorEnabled="true" MultiSelect="false" runat="server" SelectionSet="User" Width="200px" TabIndex="2" /> by using Code
public class PeoplePickerWebPart :
System.Web.UI.WebControls.WebParts.WebPart{
PeopleEditor pe;
TextBox t;
Button b;
protected override void CreateChildControls()
{
base.CreateChildControls();
pe
= new PeopleEditor();
this.Controls.Add(pe);
b = new Button();
b.Text
= "Click me to see the users";
this.Controls.Add(b);
b.Click
+= new EventHandler(b_Click);
t = new TextBox();
t.TextMode
= TextBoxMode.MultiLine;
this.Controls.Add(t);
}
void b_Click(object sender, EventArgs e)
{
foreach(string ent in pe.CommaSeparatedAccounts.Split(','))
{
t.Text += ent + Environment.NewLine;
}
}
How to display users to SharePoint People Picker control
and get data from SharePoint People Picker control
In below
example, I’ll demonstrate how to display users to people picker web control and
get data from the same control. I have field called “Staff Assigned” and its
data type is People/Group.
Below code will tell us how we can take data from that people/Group field and display to people picker SharePoint web control and also get data from people picker and give back to people/Group field from object model programmatically. //Display users from people/Group field to People Picker Control if (itmAudit["Staff Assigned"] != null) { char[] to_splitter = { ';' }; string to_list = itmAudit["Staff Assigned"].ToString(); // Reads value stored in SPList. (i.e., "Domain\User1; Domain\User2") string[] arr = to_list.Split(to_splitter); string user = string.Empty; System.Collections.ArrayList entityArrayList = new System.Collections.ArrayList(); for (int i = 1; i < arr.Length; i++) { if ((i % 2) != 0) { user = arr[i].Substring(arr[i].IndexOf("#") + 1); PickerEntity entity = new PickerEntity(); entity.Key = user; entity = userPicker.ValidateEntity(entity); entityArrayList.Add(entity); } } userPicker.UpdateEntities(entityArrayList); //Save users to people/Group field from People Picker Control SPFieldUserValueCollection values = new SPFieldUserValueCollection(); foreach (PickerEntity entity in userPicker.ResolvedEntities) { SPFieldUserValue fuv = new SPFieldUserValue(SPContext.Current.Web, Convert.ToInt16(entity.EntityData[PeopleEditorEntityDataKeys.UserId]), entity.Description); values.Add(fuv); } itmAudit["Staff Assigned"] = values;
Validation controls:
InputFormRequiredFieldValidator
InputFormRangeValidator
InputFormCompareValidator
InputFormRegularExpressionValidator
InputFormCheckBoxListValidator
InputFormCustomValidator
E.g:-
1] <spuc:InputFormRequiredFieldValidator
ID="UserNameValidator" runat="server"
Display="Dynamic" SetFocusOnError="true"
ControlToValidate="CompanyNameTextBox"
BreakBefore="true" ErrorMessage="The company name is
required" />
Input Controls
Text Box
Check Box
E.g:-
1]
<spuc:InputFormTextBox
ID="CompanyNameTextBox" runat="server"
class="ms-input"
Title="Company
name" TextMode="SingleLine" Columns="40" />
2]
<spuc:InputFormCheckBoxList
ID="SampleInputFormCheckBoxList" runat="server"
class="ms- authoringcontrols">
<asp:ListItem
Text="Option 1" Value="1" />
<asp:ListItem
Text="Option 2" Value="2" />
<asp:ListItem
Text="Option 3" Selected="True" Value="3" />
<asp:ListItem
Text="Option 4" Value="4" />
</spuc:InputFormCheckBoxList>
SPDatePickerControl
<script
type="text/javascript"
src="/_layouts/datepicker.js"></script>
<SharePoint:SPDatePickerControl
id="datePickerControl" runat="server"/>
ButtonSection
<%@ Register
TagPrefix="wssuc" TagName="ButtonSection"
src="~/_controltemplates/ButtonSection.ascx"
%>
<wssuc:ButtonSection
runat="server">
<Template_Buttons>
<asp:Button
runat="server" class="ms-ButtonHeightWidth"
OnClick="OnClickOK"
Text="<%$Resources:wss,multipages_okbutton_text%>"
id="btnOk"
accesskey="<%$Resources:wss,okbutton_accesskey%>"/>
</Template_Buttons>
</wssuc:ButtonSection>
When making use of the LayoutsPageBase in your
codebehind, you can define the URL of the Cancel button by using this
snippet:
public override string
PageToRedirectOnCancel
{
get
{
//return
base.PageToRedirectOnCancel;
return
"/_layouts/settings.aspx";
}
}
InputFormTextBox
Notice there are two InputFormTextBoxes shown here. One
with the RichTexT property set to true and the other set to false. So with a
simple property change you can get the nicely and shiny FullHTML textbox.
<SharePoint:InputFormTextBox
ID="ApproveMailSubject" RichText="false"
runat="server" Width="100%"/>
<SharePoint:InputFormTextBox
ID="ApproveMailContent" RichText="true"
RichTextMode="FullHtml"
runat="server"
TextMode="MultiLine"
Rows="20"/>
ToolBar & ToolBarButton
<%@ Register
TagPrefix="wssuc" TagName="ToolBar"
src="~/_controltemplates/ToolBar.ascx"
%>
<%@ Register
TagPrefix="wssuc" TagName="ToolBarButton"
src="~/_controltemplates/ToolBarButton.ascx"
%>
<wssuc:ToolBar
id="Toolbar" runat="server">
<template_buttons>
<wssuc:ToolBarButton
runat="server"
id="ViewSites"
Text="View
Sites"
ToolTip=""
OnClick="ViewSites_Link"
ImageUrl="/_layouts/images/newitem.gif"
Padding="2px"
AccessKey="V"
/>
</template_buttons>
<template_rightbuttons>
<SharePoint:WebApplicationSelector
id="Selector" runat="server"/>
</template_rightbuttons>
</wssuc:ToolBar>
To use the ToolBar in your WebPart you can load the
UserControls and reference them using this:
protected ToolBarButton
ToolBarButton;
protected ToolBar ToolBar;
..
//Adding a ToolBarButton
ToolBarButton =
(ToolBarButton)Page.LoadControl("/_controltemplates/ToolBarButton.ascx");
ToolBarButton.Click += new
EventHandler(ToolBarButton_Click);
ToolBarButton.Text =
"Complete selected tasks";
ToolBarButton.ImageUrl =
"/_layouts/images/CheckNames.gif";
//Adding the ToolBar
ToolBar =
(ToolBar)Page.LoadControl("/_controltemplates/ToolBar.ascx");
ToolBar.Buttons.Controls.Add(ToolBarButton);
this.Controls.Add(ToolBar);
SharePoint
Choice Field
Get value collection of a SharePoint Choice Field
public static List<string>
GetChoiceFieldValues(string listName,string fieldName, string siteCollection,
string webSite)
{ List<string> fieldList;
SPSite spSite = null;
SPWeb spWeb = null;
try
{ if (siteCollection != null) spSite = new SPSite(siteCollection); else spSite = SPContext.Current.Site;
if (webSite != null)
spWeb = spSite.OpenWeb(webSite); else spWeb = spSite.OpenWeb();
SPList spList = spWeb.Lists[listName];
SPFieldChoice field = (SPFieldChoice)spList.Fields[fieldName];
fieldList = new List<string>();
foreach (string str in field.Choices)
{ fieldList.Add(str); } } catch (Exception ex) { LogException(ex); throw; } finally { if(spWeb != null) spWeb.Close();
if(spSite != null)
spSite.Close(); }
return fieldList;
} SharePoint Validation Controls
The Microsoft.SharePoint.WebControls namespace of the Microsoft.SharePoint.dll
contains a number of validation controls that can be used on application pages and web parts to validate user entry in the SharePoint controls.
The different validation controls are:
If you want to use these SharePoint control validators, you have to add a page directive to the page:
<%@ Register TagPrefix="spuc" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
The following sections describe the use of the different SharePoint validation controls.
The InputFormRequiredFieldValidator control
This control inherits from the standard ASP.NET RequiredFieldValidator and has the same functionality.
<spuc:InputFormTextBox ID="CompanyNameTextBox" runat="server" class="ms-input" Title="Company name" TextMode="SingleLine" Columns="40" /> <spuc:InputFormRequiredFieldValidator ID="UserNameValidator" runat="server" Display="Dynamic" SetFocusOnError="true" ControlToValidate="CompanyNameTextBox" BreakBefore="true" ErrorMessage="The company name is required" />
Properties inherited from the standard ASP.NET RequiredFieldValidator control:
Important properties of the SharePoint InputFormRequiredFieldValidator control:
The InputFormRangeValidator control
This control inherits from the standard ASP.NET RangeValidator control and has the same functionality.
<spuc:InputFormTextBox ID="AgeInputFormTextBox" runat="server" class="ms-input" Title="Age" TextMode="SingleLine" Columns="3" /> <spuc:InputFormRangeValidator ID="AgeValidator" runat="server" Display="Dynamic" SetFocusOnError="true" ControlToValidate="AgeInputFormTextBox" BreakBefore="true" Type="Integer" MinimumValue="21" MaximumValue="30" ErrorMessage="You must be between 21 and 30 years old." />
Properties inherited from the standard ASP.NET RangeValidator control:
Important properties of the SharePoint InputFormRangeValidator control:
The InputFormCompareValidator control
This control inherits from the standard ASP.NET CompareValidator control and has the same functionality.
<spuc:InputFormTextBox ID="MinimumTextBox" runat="server" class="ms-input" Title="Minimum value" TextMode="SingleLine" Columns="10" /> <br /> <spuc:InputFormTextBox ID="MaximumTextBox" runat="server" class="ms-input" Title="Maximum value" TextMode="SingleLine" Columns="10" /> <spuc:InputFormCompareValidator ID="InputFormCompareValidator1" runat="server" Display="Dynamic" SetFocusOnError="true" ControlToValidate="MinimumTextBox" ControlToCompare="MaximumTextBox" Operator="LessThan" BreakBefore="true" Type="Integer" ErrorMessage="The first value must be lower than the second value." ErrorImageUrl="info.gif" />
Properties inherited from the standard ASP.NET CompareValidator control:
Important properties of the SharePoint InputFormCompareValidator control:
It is slightly different if you want to validate a date entered in a SharePoint DateTimeControl. This control is a composite control and you have to validate the date entered in the Date control:
<spuc:DateTimeControl ID="StartDateControl" runat="server" DateOnly="true" /> <spuc:InputFormCompareValidator ID="InputFormCompareValidator2" runat="server" Display="Dynamic" SetFocusOnError="true" ControlToValidate="StartDateControl$StartDateControlDate" Type="Date" Operator="DataTypeCheck" BreakBefore="true" ErrorMessage="Please enter a valid date." ErrorImageUrl="info.gif" />
I got the milk from Greg Galipeau’s blog in his post about validating an DateTimeControl with a standard ASP.NETCompare validator.
The InputFormRegularExpressionValidator control
This validator control can be used to validate user input against a regular expression. It inherits from the standardASP.NET RegularExpressionValidator. Following example checks wether the user entered a valid email address.
<spuc:InputFormTextBox ID="EmailTextBox" runat="server" class="ms-input" Title="Email" TextMode="SingleLine" Columns="60" /> <spuc:InputFormRegularExpressionValidator ID="Validator" runat="server" Display="Dynamic" SetFocusOnError="true" ControlToValidate="EmailTextBox" ValidationExpression="^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$" ErrorMessage="Enter a valid email address." />
Properties inherited from the ASP.NET RegularExpressionValidator control:
Important properties of the SharePoint InputFormRegularExpressionValidator control:
The InputFormCheckBoxListValidator control
This validator control can only be used against an InputFormCheckBoxList control (and not against an InputFormCheckBox control). It works as a required field validator: if no options are selected when clicking the OK button, the specified error message will appear:
<spuc:InputFormCheckBoxList ID="SampleInputFormCheckBoxList" runat="server" class="ms-authoringcontrols"> <asp:ListItem Text="Option 1" Value="1" /> <asp:ListItem Text="Option 2" Value="2" /> <asp:ListItem Text="Option 3" Selected="True" Value="3" /> <asp:ListItem Text="Option 4" Value="4" /> </spuc:InputFormCheckBoxList> <spuc:InputFormCheckBoxListValidator ID="SampleCheckBoxValidator" runat="server" ControlToValidate="SampleInputFormCheckBoxList" ErrorMessage="This is a sample error message." />
If you try to use it in combination with a InputFormCheckBox control, you will get an unclear error message (not informing you about the real problem) but when looking with Reflector into the code, it learns you that the control referenced in the ControlToValidate property is casted to an InputFormCheckBoxList control.
The InputFormCustomValidator control
If one of the previous validation controls does not suit your needs, you can define a custom validation function. You have the choice to define a client-side validation function or a server-side validation function, or combine both. Best practice is to perform server-side validation, even if you use a client-side check because some smartasses can try to bypass your client-side script.
This is an example of server-side validation:
<spuc:InputFormTextBox ID="UsernameTextBox" runat="server" class="ms-input" Title="Username" TextMode="SingleLine" Columns="60" /> <spuc:InputFormCustomValidator ID="UsernameCustomValidator" runat="server" Display="Dynamic" SetFocusOnError="true" ControlToValidate="UsernameTextBox" OnServerValidate="ValidateUserName" ErrorMessage="Your user name must be at least 10 characters long (server-side validation)." ValidateEmptyText="true" />
In your code-behind you define the controls as protected class-level variables:
protected InputFormTextBox UsernameTextBox; protected InputFormCustomValidator UsernameCustomValidator;
And you add the server-side validation method. This method accepts 2 incoming arguments: a source object being the control to validate, and a args object having properties as Value and IsValid. The Value property contains the value to validate. Set the IsValid property to true if the validation is successful or set the IsValid property to false if the validation fails.
protected void ValidateUserName(object source, ServerValidateEventArgs args)
{
if (args.Value.Length >= 10)
args.IsValid = true;
else
args.IsValid = false;
}
Properties inherited from the ASP.NET CustomValidator control:
A lot of people combine a custom validator control with a RequiredFieldValidator but this is not necessary because theASP.NET CustomValidator control (and thus also the InputFormCustomValidator control) has a ValidateEmptyText property which can be set to true or false. If set to false, a blank entry is validated as a valid entry. If set to true, a blank entry will be considered as erroneous, thus excluding the need for aRequiredFieldValidator control.
If you want to use client-side validation, you have to set the ClientValidationFunction property. The value must be the name of a javascript function.
<spuc:InputFormTextBox ID="UsernameTextBox" runat="server" class="ms-input" Title="Username" TextMode="SingleLine" Columns="60" /> <spuc:InputFormCustomValidator ID="UsernameCustomValidator" runat="server" Display="Dynamic" SetFocusOnError="true" ControlToValidate="UsernameTextBox" ClientValidationFunction="IsValidUsername" ErrorMessage="Your user name must be at least 10 characters long (client-side validation)." ValidateEmptyText="true" />
The javascript function must reside in the <asp:Content> placeholder with ContentPlaceHolderID PlaceHolderMain(where most of your controls reside). The function needs 2 arguments: a source object, being the control that needs validation; and an arguments object having properties like Value and IsValid. If you want the validation to succeed, you have to set args.IsValid to true; if you want the validation to fail, you have to set args.IsValid to false.
<asp:Content ID="Main" runat="server" ContentPlaceHolderID="PlaceHolderMain"> <script language="javascript"> function IsValidUsername(source, args) { if (args.Value.length >= 10) args.IsValid = true; else args.IsValid = false; } </script> <!- - rest of the controls--> </asp:Content>
Important properties of the SharePoint InputFormCustomValidator control:
ValidationSummary control
You can combine any SharePoint validation control with the ASP.NET ValidationSummary control. There is no counterpart for it in SharePoint.
When you use no ValidationSummary control, all error messages appear next to or right under the control that fails validation. A ValidationSummary control presents the user with a lsit of validation errors at the bottom of the page.
You add a ValidationSummary control to your application page or web part as follows:
<asp:ValidationSummary ID="SharePointValidationSummary" runat="server" DisplayMode="BulletList" ShowSummary="true" HeaderText="Please correct the following errors:" />
The different propeties on the ValidationSummary control are:
Normally you should also be able to set the Text property of the SharePoint validation controls to f.e. * to display an asterisk next to the control that failed validation but after a look inside the Microsoft.SharePoint.dll with Reflector it show that the Text property is overridden and looses its original meaning.
|
No comments:
Post a Comment