Thursday, March 1, 2012

Article 2: Get Choice Field from sharepoint list and fill to checkboxlist


Step 1: Create List name GetChoiceFields, Field name is Provinces as below
Step 2: User Interface
Step 3: Open VS 2010 | New Project | Empty Sharepoint Project | name GetChoiceFields | Choose deploy sanbox solution
Step 4: Add new item | Web Part | name GetChoiceFields
Step 5: Paste code to your project
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace GetChoiceFields.GetChoiceFields
{
[ToolboxItemAttribute(false)]
public class GetChoiceFields : WebPart
{
CheckBoxList cblProvinces = null;
protected override void CreateChildControls()
{
cblProvinces = new CheckBoxList();
this.Controls.Add(cblProvinces);           
GetDataInChoiceFieldAndFillToCheckBoxListControl();
}
void GetDataInChoiceFieldAndFillToCheckBoxListControl()
{
try
{
using (SPSite spSite = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb spWeb = spSite.OpenWeb())
{
SPList spList = spWeb.Lists["GetChoiceFields"];//GetChoiceFields => Display Name
SPFieldMultiChoice spFieldMultiChoice = (SPFieldMultiChoice)spList.Fields["Provinces"];//Provinces => internal name                       
for (int item = 0; item < spFieldMultiChoice.Choices.Count; item++)
{
cblProvinces.Items.Add(new ListItem(spFieldMultiChoice.Choices[item], spFieldMultiChoice.Choices[item]));
}
}
}
}
catch (Exception ex)
{

}
}
}
}
Step 6: Build project | Package project to .wsp. Open your site, on top level site | Click Site Actions | Site Setting | Click Solution | Upload .wsp to here
Step 7: Active .wsp
Step 8: Open any page and Add web part. Result below

0 comments:

Post a Comment