How to Use SPForm and SPFormCollection
When writing WebParts that are going to heavily interact with lists, you will end up working with the associated form pages that are offered when massaging list items, so, you will end up working with the SPForm and SPFormCollection class. An SPForm The SPForm and SPFormCollection class derives from the Microsoft.SharePoint namespace, and while the SPForm object simply represents one of the forms associated with the list, the SPFormCollection is just a collection of those same SPForm objects.
So, let’s firstly look at some of the basic code required to interact with these pieces. What I want to show you how to do right now is iterate through a set of form objects contain in a form collection. While iterating through the SPForm objects in SPFormsCollection, we can then use the Microsoft.SharePoint.PAGETYPE enumeration which contains the types of available forms, and the Type property of the SPForm object in order to build a simple operator comparison. In the last part, you can see after the test that we are assigning the url strings (which will be consumed in a minute) with the site url (which is just passed in via a SPSite site = new SPSite(this.myUrl); and then using the OpenWeb() method), and then appending the secondary portion using the url property of the SPForm object.
- public SPFormCollection formsCollection;
- public string viewItemUrl = "";
- public string newItemUrl = "";
- public string editItemUrl = "";
- foreach (SPForm form in this.formsCollection)
- if (form.Type == PAGETYPE.PAGE_NEWFORM)
- this.newItemUrl = this.myUrl + "/" + form.Url;
- if (form.Type == PAGETYPE.PAGE_EDITFORM)
- this.editItemUrl = this.myUrl + "/" + form.Url;
- if (form.Type == PAGETYPE.PAGE_DISPLAYFORM)
- this.viewItemUrl = this.myUrl + "/" + form.Url;
So, now you have a test, which is great. But what can I do with it? Well, the most common use for this type of loop is to make your own item links for hooking up to items in a SharePoint list. Let’s use the viewItemUrl string as an example.
Now that you have the viewItemUrl string populated, you can use the ID property of a SharePoint List object (which you could collect all of them in an SPListItemCollection doing something like foreach (SPListItem item in SPListItemCollection )), and create fun links to create list interactivity in your WebParts.
- output.Write("<a xhref='" + this.viewItemUrl + "?ID=" + item.ID.ToString() + "' target='_self'>");