使用SharePoint对象SPFieldCollection获取列表所有字段信息
使用SharePoint对象模型的SPFieldCollection对象可以很容易的获取到某个列表SPList中所有定义的字段信息,主要包括信息:字段类型(TypeDisplayName)、内部名称(InternalName)、显示名称(Title,在字段内部,显示名称使用Title表示)、SchemaXml、ID等信息。通过这些信息可以具体的了解到此列表中字段的详细信息,可以更容易的通过对象模型操作此列表。下面我们通过一段简单的代码,将通知(Announcements)列表中的所有定义的字段信息使用GridView控件呈现出来。C#代码如下:
view source
print?
01using System;
02using System.Web.UI;
03using System.Web.UI.WebControls;
04using System.Web.UI.WebControls.WebParts;
05
06using System.Collections.Specialized;
07using Microsoft.SharePoint;
08
09namespace Example.SharePoint.SPField
10{
11 public partial class SPFieldWebPartUserControl : UserControl
12 {
13 protected void Page_Load(object sender, EventArgs e)
14 {
15 }
16
17 /// <summary>
18 /// 根据SPWeb,列表名称获取列表中的所有字段
19 /// </summary>
20 /// <param name="web"></param>
21 /// <param name="listName"></param>
22 /// <returns></returns>
23 protected SPFieldCollection GetAllSPFieldInfo(SPWeb web, string listName)
24 {
25 SPFieldCollection fieldColl = null;
26 if (web != null && !string.IsNullOrEmpty(listName))
27 {
28 SPList list = web.Lists;
29 fieldColl = list.Fields;
30 }
31 return fieldColl;
32 }
33
34
35 /// <summary>
36 /// 提交
37 /// </summary>
38 /// <param name="sender"></param>
39 /// <param name="e"></param>
40 protected void Button1_Click(object sender, EventArgs e)
41 {
42 this.gV.DataSource = this.GetAllSPFieldInfo(SPContext.Current.Web, "Announcements");
43 this.gV.DataBind();
44 }
45 }
46}上面的代码中,主要是使用了SPList.Fields来获取此列表中所有的字段,返回的集合类型为:SPFieldCollection,这是一个集合类型,可以直接将此类型绑定到ASP.NET的GridView控件并显示出来。
在这里要注意,我们在按钮事件中是使用了SPContext.Current.Web来获取此代码运行的当前网站。这样做的好处是以后不管此代码运行在任何的SharePoint环境中不需要做任何修改即可正常运行。
还有一点就是我们在上面的代码中,使用了:
SPFieldCollection fieldColl = null;
来存储SPList.Fields获取的所有字段集合,这样可以提高性能,将所有的字段暂存到SPFieldCollection集合类型中,这样每次调用时不用再重新获取。大大提高了读取的速度。
上面的代码是编写在一个叫做SPFieldWebPart的可视Web部件中,用户控件ASCX布局代码如下:
view source
print?
01<div>
02
03 <asp:Button ID="Button1" runat="server" Text="Submit"/></div>
04
05<div>
06
07 <asp:GridView ID="gV" AutoGenerateColumns="false" runat="server">
08
09 <Columns>
10
11 <asp:BoundField DataField="TypeDisplayName" HeaderText="TypeDisplayName" />
12
13 <asp:BoundField DataField="InternalName" HeaderText="InternalName" />
14
15 <asp:BoundField DataField="Title" HeaderText="Title" />
16
17 <asp:BoundField DataField="Scope" HeaderText="Scope" />
18
19 <asp:BoundField DataField="ID" HeaderText="ID" />
20
21 <asp:BoundField DataField="SchemaXml" HeaderText="SchemaXml" />
22
23 </Columns>
24
25 </asp:GridView>
26
27</div>将上面的可视Web部件使用VS2010部署到SharePoint环境中,如图1所示:
要看图的请查看全文:http://www.360sps.com/item/9154ff6b4de04991b0674c624e6f09fe.aspx
页:
[1]