Author Archive

Specify What Forms a Field Shows Up On

Thursday, October 4th, 2007

I am often asked about field level security in SharePoint. Well, SharePoint does not have field level security but it does have the ability to specify which forms a field will show up on. For example, we can have a field show up on the New form and all view forms but not on the edit form. This is by no means security, but it does allow for certain  scenarios, like after a value is entered it cannot be changed. So, this post will show you how to change those settings on fields.

There are 2 different ways to set these properties. The first is through the list definition. When we create a list definition we can certain attributes on the Field element tag as follows.

  • ShowInEditForm – Determines if this field shows up in the Edit form for a specific field.
  • ShowInNewForm – Determines if this field show up in the New form for adding a new item to this list.
  • ShowInVersionHistory – Determines if this field shows up in the version details of a list item.
  • ShowInViewForms – Determines if this field shows up in the any View forms for a specific item.

This post is going to show you the second way, in code, to set these properties. Through the SharePoint API you can also set these properties of a specific field. These are optional value fields, meaning that they can be null. So the first time you look at these, they might have a null value in them.

The first thing we need to do is get a reference to the list that contains the field that we want to set these values on.

// Create the site that contains our list
SPSite oSite = new SPSite(strSiteUrl);

// Open the web object
SPWeb oWeb = spSite.OpenWeb();

// Get the list that contains the field we want to change the settings on
SPList oList = oWeb.Lists["Contacts"];

Now that we have our list, we need to get the field that we want to set the settings on.

// Get the field that we want to change the settings on
SPField oField = oList.Fields["Title"];

Now we can set the properties of our field according to our requirements. There are a couple more properties available in the API than there are in the List Definition schema.

// Set the field properties
oField.ShowInDisplayForm = true;     // Determines in this field shows on the display item form.
oField.ShowInEditForm = false;        // Determines if this field shows on the edit item form.
oField.ShowInListSettings = true;     // Determines if this field shows on the list settings page.
oField.ShowInNewForm = true;        // Determines if this field shows on the new item form.
oField.ShowInVersionHistory = true;// Determines if this field shows on the version history pages.
oField.ShowInViewForms = true;    // Determines in this field shows on the all view forms pages.

Now all we have to do is call the update method on the field object to actually update the settings and save the changes back to the database.

// Update the field
oField.Update();

Continue reading if you want to see how to accomplish the same tasks in SWAT (SharePoint Work Acceleration Toolkit). You can find SWAT here http://www.idevfactory.com

Set Field Settings

In the Farm Tree window, rick click on the site that you want to set the web parts properties for and click Show Site Details. This will load all the details for that site.

In the Site Details section, select the Site Lists tab.

In the Site Lists tab, right click on the list that has the field that you want to set the properties on and click Show List Details.

On the List Details window, right click on the field that you want to set the properties for and click Show Field Settings.

On the Field Details window, select the specific settings that you want to change and click Update.

Enjoy!!!

Specify What Forms a Field Shows Up On

Thursday, October 4th, 2007

I am often asked about field level security in SharePoint. Well, SharePoint does not have field level security but it does have the ability to specify which forms a field will show up on. For example, we can have a field show up on the New form and all view forms but not on the edit form. This is by no means security, but it does allow for certain  scenarios, like after a value is entered it cannot be changed. So, this post will show you how to change those settings on fields.

There are 2 different ways to set these properties. The first is through the list definition. When we create a list definition we can certain attributes on the Field element tag as follows.

  • ShowInEditForm – Determines if this field shows up in the Edit form for a specific field.
  • ShowInNewForm – Determines if this field show up in the New form for adding a new item to this list.
  • ShowInVersionHistory – Determines if this field shows up in the version details of a list item.
  • ShowInViewForms – Determines if this field shows up in the any View forms for a specific item.

This post is going to show you the second way, in code, to set these properties. Through the SharePoint API you can also set these properties of a specific field. These are optional value fields, meaning that they can be null. So the first time you look at these, they might have a null value in them.

The first thing we need to do is get a reference to the list that contains the field that we want to set these values on.

// Create the site that contains our list
SPSite oSite = new SPSite(strSiteUrl);

// Open the web object
SPWeb oWeb = spSite.OpenWeb();

// Get the list that contains the field we want to change the settings on
SPList oList = oWeb.Lists["Contacts"];

Now that we have our list, we need to get the field that we want to set the settings on.

// Get the field that we want to change the settings on
SPField oField = oList.Fields["Title"];

Now we can set the properties of our field according to our requirements. There are a couple more properties available in the API than there are in the List Definition schema.

// Set the field properties
oField.ShowInDisplayForm = true;     // Determines in this field shows on the display item form.
oField.ShowInEditForm = false;        // Determines if this field shows on the edit item form.
oField.ShowInListSettings = true;     // Determines if this field shows on the list settings page.
oField.ShowInNewForm = true;        // Determines if this field shows on the new item form.
oField.ShowInVersionHistory = true;// Determines if this field shows on the version history pages.
oField.ShowInViewForms = true;    // Determines in this field shows on the all view forms pages.

Now all we have to do is call the update method on the field object to actually update the settings and save the changes back to the database.

// Update the field
oField.Update();

Continue reading if you want to see how to accomplish the same tasks in SWAT (SharePoint Work Acceleration Toolkit). You can find SWAT here http://www.idevfactory.com

Set Field Settings

In the Farm Tree window, rick click on the site that you want to set the web parts properties for and click Show Site Details. This will load all the details for that site.

In the Site Details section, select the Site Lists tab.

In the Site Lists tab, right click on the list that has the field that you want to set the properties on and click Show List Details.

On the List Details window, right click on the field that you want to set the properties for and click Show Field Settings.

On the Field Details window, select the specific settings that you want to change and click Update.

Enjoy!!!

Working With Web Parts Through Code

Wednesday, October 3rd, 2007

This post will show you how to work with web parts through code. Often times there is a need to work with web parts through the API. You can import, export, add remove as well as change settings of web parts.

Importing and Adding Web Parts.

The first thing we need to get is out site and web object.

SPSite oSite = new SPSite("http://yoursiteurl");
SPWeb oWeb = oSite.OpenWeb();

The next thing we need to get is the page (file) that we want to import the web part on. For this example we will be working with the default.aspx page on a team site.

SPFile oFile = oWeb.GetFIle("default.aspx");

After we have a file object we can get the limited web part manager. The limited web part manager is what we use to do all of our web part operations.

Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager oWebPartManager = oFile.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);

Now we need to create a StringReader class. The constructor we are using takes a string as a parameter. This is simply the xml file of the web part that we want to import. (The web part .dwp or .webpart file).

System.IO.StringReader oReader = new StringReader(<<web part xml file (.dwp or .webpart file string contents>>);

Now we need to create a XmlReader and pass in our string reader.

XmlTextReader oXmlReader = new XmlTextReader(oReader);

We need to create a string for our output message.

string strErrorMessage = "";

No back to our web part manager, we need to import the web part. We simply call the ImportWebPart method on our limited web part manager object. The first parameter is the xml reader we created before and the second parameter is the output message passed back to us as a out parameter. This method will return a WebPart object.

System.Web.UI.WebControls.WebParts.WebPart oWebPart = spWebPartManager.ImportWebPart(xmlReader, out strErrorMessage);

No that we have the web part, we can set specific settings that we want to control for our web part. For example, if we don't want the close x to show up on the top right of the web part we could set the AllowHide property of the web part.

oWebPart.AllowClose = false;

No that we have actually imported the web part we need to actually add it to the site. We do this by calling the AddWebPart method on the limited web part manager. The first parameter is the web part that we imported in the previous step. The second parameter is the  zone id (as a string) that you want to add the web part to and the third parameter is the zone order (index).

oWebPartManager.AddWebPart(oWebPart, "left", 1);

Full code listing.

// Get the site
SPSite oSite = new SPSite("http://yoursiteurl");

// Get the web we are going to import and add the web part to
SPWeb oWeb = oSite.OpenWeb();

// Get the file (page) that we want to add the web part to
SPFile oFile = oWeb.GetFIle("default.aspx");

// Get the limited web part manager
Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager oWebPartManager = oFile.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);

// Create the string reader for the web part .dwp or .webpart file.
System.IO.StringReader oReader = new StringReader(<<web part xml file (.dwp or .webpart file string contents>>);

// Create the xml text reader to read the string into
XmlTextReader oXmlReader = new XmlTextReader(oReader);

// Create the error message that will get passed back
string strErrorMessage = "";

// Import the web part
System.Web.UI.WebControls.WebParts.WebPart oWebPart = spWebPartManager.ImportWebPart(xmlReader, out strErrorMessage);

// Now actually add the web part to the page
oWebPartManager.AddWebPart(oWebPart, "left", 1);

NOTE: You can also remove and export web parts through the limited web part manager.

Continue reading if you want to see how to accomplish the same tasks in SWAT (SharePoint Work Acceleration Toolkit). You can find SWAT here http://www.idevfactory.com

Set Web Part Properties

In the Farm Tree window, rick click on the site that you want to set the web parts properties for and click Show Site Details. This will load all the details for that site.

In the Site Details section, select the Site Pages tab.

In the Site Pages tab, right click on the page you want to look at the web parts of and click Show Page Web Parts.

On the Page Web Parts window, right click on the web part that you want to set the settings on and click Web Part Properties.

On the Web Part Properties window, select the specific properties you wish to set and click Update.

NOTE: You can also close and open a web part from this screen as well.

NOTE: Under the Wizards menu of SWAT, there a 3 different wizards dealing with web parts. Add Web Parts, Replicate Web Parts and Delete Web Parts. These wizards allow you to work with many web parts on many different sites all in one action.

Enjoy!!!

Working With Web Parts Through Code

Wednesday, October 3rd, 2007

This post will show you how to work with web parts through code. Often times there is a need to work with web parts through the API. You can import, export, add remove as well as change settings of web parts.

Importing and Adding Web Parts.

The first thing we need to get is out site and web object.

SPSite oSite = new SPSite("http://yoursiteurl");
SPWeb oWeb = oSite.OpenWeb();

The next thing we need to get is the page (file) that we want to import the web part on. For this example we will be working with the default.aspx page on a team site.

SPFile oFile = oWeb.GetFIle("default.aspx");

After we have a file object we can get the limited web part manager. The limited web part manager is what we use to do all of our web part operations.

Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager oWebPartManager = oFile.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);

Now we need to create a StringReader class. The constructor we are using takes a string as a parameter. This is simply the xml file of the web part that we want to import. (The web part .dwp or .webpart file).

System.IO.StringReader oReader = new StringReader(<<web part xml file (.dwp or .webpart file string contents>>);

Now we need to create a XmlReader and pass in our string reader.

XmlTextReader oXmlReader = new XmlTextReader(oReader);

We need to create a string for our output message.

string strErrorMessage = "";

No back to our web part manager, we need to import the web part. We simply call the ImportWebPart method on our limited web part manager object. The first parameter is the xml reader we created before and the second parameter is the output message passed back to us as a out parameter. This method will return a WebPart object.

System.Web.UI.WebControls.WebParts.WebPart oWebPart = spWebPartManager.ImportWebPart(xmlReader, out strErrorMessage);

No that we have the web part, we can set specific settings that we want to control for our web part. For example, if we don't want the close x to show up on the top right of the web part we could set the AllowHide property of the web part.

oWebPart.AllowClose = false;

No that we have actually imported the web part we need to actually add it to the site. We do this by calling the AddWebPart method on the limited web part manager. The first parameter is the web part that we imported in the previous step. The second parameter is the  zone id (as a string) that you want to add the web part to and the third parameter is the zone order (index).

oWebPartManager.AddWebPart(oWebPart, "left", 1);

Full code listing.

// Get the site
SPSite oSite = new SPSite("http://yoursiteurl");

// Get the web we are going to import and add the web part to
SPWeb oWeb = oSite.OpenWeb();

// Get the file (page) that we want to add the web part to
SPFile oFile = oWeb.GetFIle("default.aspx");

// Get the limited web part manager
Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager oWebPartManager = oFile.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);

// Create the string reader for the web part .dwp or .webpart file.
System.IO.StringReader oReader = new StringReader(<<web part xml file (.dwp or .webpart file string contents>>);

// Create the xml text reader to read the string into
XmlTextReader oXmlReader = new XmlTextReader(oReader);

// Create the error message that will get passed back
string strErrorMessage = "";

// Import the web part
System.Web.UI.WebControls.WebParts.WebPart oWebPart = spWebPartManager.ImportWebPart(xmlReader, out strErrorMessage);

// Now actually add the web part to the page
oWebPartManager.AddWebPart(oWebPart, "left", 1);

NOTE: You can also remove and export web parts through the limited web part manager.

Continue reading if you want to see how to accomplish the same tasks in SWAT (SharePoint Work Acceleration Toolkit). You can find SWAT here http://www.idevfactory.com

Set Web Part Properties

In the Farm Tree window, rick click on the site that you want to set the web parts properties for and click Show Site Details. This will load all the details for that site.

In the Site Details section, select the Site Pages tab.

In the Site Pages tab, right click on the page you want to look at the web parts of and click Show Page Web Parts.

On the Page Web Parts window, right click on the web part that you want to set the settings on and click Web Part Properties.

On the Web Part Properties window, select the specific properties you wish to set and click Update.

NOTE: You can also close and open a web part from this screen as well.

NOTE: Under the Wizards menu of SWAT, there a 3 different wizards dealing with web parts. Add Web Parts, Replicate Web Parts and Delete Web Parts. These wizards allow you to work with many web parts on many different sites all in one action.

Enjoy!!!

Setting Permissions Through Code

Sunday, September 30th, 2007

I seam to always get asked this question on every project. This will be a very basic post to show you how to assign permissions through the SharePoint API.

When working with permissions through the SharePoint API, there are some key objects to take note of.

  • SPUser – A actual security object in SharePoint (AD User, AD Group or Forms Based User or Group).
  • SPGroup – A SharePoint group defined through SharePoint.
  • SPRoleDefinition – A actual role (permission level) defined in SharePoint (Read, Full Control etc…)
  • SPRoleAssignment – The actual assignment between a SPUser/SPGroup and a SPRoleDefinition

Assign a User to a SharePoint Group

To assign a user to a SharePoint group we need to get the SPGroup object and add a user with the AddUser method. This method has 2 overloads, the first takes a SPUser object and the second takes some specific parameters (login name, email, name, notes). Below is the code in both formats.

// ******************** Adding a SPUser to a SharePoint Group ********************
// Create the site that contains our list
SPSite oSite = new SPSite("<<my site url>>");

// Open the web object
SPWeb oWeb = spSite.OpenWeb();

// Get the group that we want to add the user to
SPGroup oGroup = oWeb.Groups["<<group name>>"];

// Get the user that we want to add to the group
SPUser oUser = oWeb.AllUsers["domainlogin"];

// Now we add the user to the groups user collection
oGroup.AddUser(oUser);

// Update the group
oGroup.Update();

// ******************** Adding a User to a SharePoint Group ********************
// Create the site that contains our list
SPSite oSite = new SPSite("<<my site url>>");

// Open the web object
SPWeb oWeb = spSite.OpenWeb();

// Get the group that we want to add the user to
SPGroup oGroup = oWeb.Groups["<<group name>>"];

// Now we add the user to the groups user collection
oGroup.AddUser("login", "email", "name", "notes");

// Update the group
oGroup.Update();

Assigning Roles (Permission Levels) to a User or SharePoint Group

To assign permission to a user (account) or a SharePoint group there are some objects that we need to look at in a certain order. The first thing we need to do is get the the security principal that we want to assign the role to (SPUser or SPGroup). The next thing we need to do it get the actual permission (role) that we want to assign (ex: Read, Full Control etc…). Then we need to create a SPRoleAssignment object and on the constructor pass it in the SPUser or SPGroup (security principal) that we want to assign the permissions to. Now we need to add the role definition to the RoleDefinitionBindings collection of the role assignment object. Then we need to add the actual role assignment to the web (site) and update the web. Below is the full code lisitng.

// Create the site that contains our list
SPSite oSite = new SPSite("<<my site url>>");

// Open the web object
SPWeb oWeb = oSite.OpenWeb();

// Get the group that we want to add the user to
SPGroup oGroup = oWeb.Groups["<<group name>>"];

// Get the role definition we want to assign ex: Full Control
SPRoleDefinition oRole = oWeb.RoleDefinitions["<< role name>>"];

// Create the role assignment object
SPRoleAssignment oRoleAssignment = new SPRoleAssignment(oGroup);

// Add the role definition to the role assignemnt.
// This will assign the specific permission to the security principal for this role assignemnt.
oRoleAssignment.RoleDefinitionBindings.Add(oRole);

// Now we need to add the role assignment to the web
oWeb.RoleAssignments.Add(oRoleAssignment);

// Now update the web
oWeb.Update();

Enjoy!!!

Setting Permissions Through Code

Sunday, September 30th, 2007

I seam to always get asked this question on every project. This will be a very basic post to show you how to assign permissions through the SharePoint API.

When working with permissions through the SharePoint API, there are some key objects to take note of.

  • SPUser – A actual security object in SharePoint (AD User, AD Group or Forms Based User or Group).
  • SPGroup – A SharePoint group defined through SharePoint.
  • SPRoleDefinition – A actual role (permission level) defined in SharePoint (Read, Full Control etc…)
  • SPRoleAssignment – The actual assignment between a SPUser/SPGroup and a SPRoleDefinition

Assign a User to a SharePoint Group

To assign a user to a SharePoint group we need to get the SPGroup object and add a user with the AddUser method. This method has 2 overloads, the first takes a SPUser object and the second takes some specific parameters (login name, email, name, notes). Below is the code in both formats.

// ******************** Adding a SPUser to a SharePoint Group ********************
// Create the site that contains our list
SPSite oSite = new SPSite("<<my site url>>");

// Open the web object
SPWeb oWeb = spSite.OpenWeb();

// Get the group that we want to add the user to
SPGroup oGroup = oWeb.Groups["<<group name>>"];

// Get the user that we want to add to the group
SPUser oUser = oWeb.AllUsers["domainlogin"];

// Now we add the user to the groups user collection
oGroup.AddUser(oUser);

// Update the group
oGroup.Update();

// ******************** Adding a User to a SharePoint Group ********************
// Create the site that contains our list
SPSite oSite = new SPSite("<<my site url>>");

// Open the web object
SPWeb oWeb = spSite.OpenWeb();

// Get the group that we want to add the user to
SPGroup oGroup = oWeb.Groups["<<group name>>"];

// Now we add the user to the groups user collection
oGroup.AddUser("login", "email", "name", "notes");

// Update the group
oGroup.Update();

Assigning Roles (Permission Levels) to a User or SharePoint Group

To assign permission to a user (account) or a SharePoint group there are some objects that we need to look at in a certain order. The first thing we need to do is get the the security principal that we want to assign the role to (SPUser or SPGroup). The next thing we need to do it get the actual permission (role) that we want to assign (ex: Read, Full Control etc…). Then we need to create a SPRoleAssignment object and on the constructor pass it in the SPUser or SPGroup (security principal) that we want to assign the permissions to. Now we need to add the role definition to the RoleDefinitionBindings collection of the role assignment object. Then we need to add the actual role assignment to the web (site) and update the web. Below is the full code lisitng.

// Create the site that contains our list
SPSite oSite = new SPSite("<<my site url>>");

// Open the web object
SPWeb oWeb = oSite.OpenWeb();

// Get the group that we want to add the user to
SPGroup oGroup = oWeb.Groups["<<group name>>"];

// Get the role definition we want to assign ex: Full Control
SPRoleDefinition oRole = oWeb.RoleDefinitions["<< role name>>"];

// Create the role assignment object
SPRoleAssignment oRoleAssignment = new SPRoleAssignment(oGroup);

// Add the role definition to the role assignemnt.
// This will assign the specific permission to the security principal for this role assignemnt.
oRoleAssignment.RoleDefinitionBindings.Add(oRole);

// Now we need to add the role assignment to the web
oWeb.RoleAssignments.Add(oRoleAssignment);

// Now update the web
oWeb.Update();

Enjoy!!!

Generating Test Data

Thursday, September 27th, 2007

Often times there is a need to have some good test data in lists or libraries for development, testing and demos. This post is specific to the SharePoint Work Acceleration Toolkit (SWAT) from iDevFactory. You can find the tool here http://www.idevfactory.com

SWAT has the capability to generate random child sites as well as documents (and metadata) for document libraries and list items for lists. This post will show you how to generate random documents for a document library.

In the Farm Tree window, right click on the site that you want to generate the test data on and select Show Site Details.

In the Site Details section, select the Site Lists tab.

In the Site Lists tab, right click on the document library that you want to generate test data for and select Generate Test Data

On the Generate Test Data screen, for the # of Items to Generate enter 500.

On the Generate Test Data screen, right click on the Title field and select Set Field Parameters.

On the Field Parameters screen, select Sentence and click Ok. This will generate a sentence instead of a single word for the Title field.

On the Generate Test Data screen, click Ok. This will kick off the process for generating our test data.

After the process is done generating our test data, we can navigate to that document libraries page and see the test data that got generated.

Enjoy!!!

Generating Test Data

Thursday, September 27th, 2007

Often times there is a need to have some good test data in lists or libraries for development, testing and demos. This post is specific to the SharePoint Work Acceleration Toolkit (SWAT) from iDevFactory. You can find the tool here http://www.idevfactory.com

SWAT has the capability to generate random child sites as well as documents (and metadata) for document libraries and list items for lists. This post will show you how to generate random documents for a document library.

In the Farm Tree window, right click on the site that you want to generate the test data on and select Show Site Details.

In the Site Details section, select the Site Lists tab.

In the Site Lists tab, right click on the document library that you want to generate test data for and select Generate Test Data

On the Generate Test Data screen, for the # of Items to Generate enter 500.

On the Generate Test Data screen, right click on the Title field and select Set Field Parameters.

On the Field Parameters screen, select Sentence and click Ok. This will generate a sentence instead of a single word for the Title field.

On the Generate Test Data screen, click Ok. This will kick off the process for generating our test data.

After the process is done generating our test data, we can navigate to that document libraries page and see the test data that got generated.

Enjoy!!!

Create Your Own Data Entry Form Web Part

Monday, September 24th, 2007

There are many scenarios that I always run into on projects or client sites that we need to create our own data entry forms for lists. Microsoft has really done a lot of work around this in exposing the objects that SharePoint uses so we can reuse these and have the same SharePoint look and feel. This post will show you how to build a data entry web part that uses the same objects that SharePoint does.

There are many discussion on creating web parts and rendering the controls that you create onto web parts. This post will not go into that, but will focus on the objects for a data entry form.

The control that we are dealing with is in the Microsoft.SharePoint.WebControls namespace. There are a couple things that you would want to determine before you actually create and render the control, like if the field is hidden or read only etc… After we determine if this field should be created and displayed we simply create a control called  FormField. Once we create this control you simply set a couple properties and SharePoint will take care of the rest. The 3 main properties are ControlMode, ListId and FieldName. ControlMode tells the control which mode that this form is in (Display, Edit and New). The ListId tells the control which list on the site to hook to and FieldName tells the control which field that this control is attached to in the list. There is a fourth property to set if we are in Edit or Display mode and that is ItemId. If we set ItemId and are in Edit or Display mode, then SharePoint will automatically set the control value to that specific items value in the list. After we have added all of our fields, we can create a SaveButton control (In the same namespace, Microsoft.SharePoint.WebControls). You would also set the ControlMode and ListId properties on the save button to hook that specific button to the list as well. Once you have done all that, all you would need to do is add the controls created to your web parts collection (or however you render your controls inside a web part). Once you have the controls showing up, you can enter and edit data, click Save and SharePoint will take care of determining which list and item to hook to and actually updating the correct list item with the new values. There is also a property on the SaveButton called RedirectUrl. If you do not set this property, once the user hits Save it will automatically redirect the user back to the default list page. If you choose, you can set this property back to the calling page or a different page of your choice and when the user hits Save, they will be redirected back to that page. So you can build web parts that mimic the SharePoint data entry forms without the user ever having to go to the list itself. The other control we are using is the FieldLabel control. The FieldLabel control will render the actual label for that specific field. Below is the full code listing to render the web part.

// Create the table object that we are going to add the rows and cells to for our data entry form
Table oTable = new Table();
oTable.CellPadding = 0;
oTable.CellSpacing = 0;

// Get the site that this web part is running on.
SPWeb oWeb = Microsoft.SharePoint.WebControls.SPControl.GetContextWeb(Context);

// Get the list we are going to work with
SPList oList = oWeb.Lists["Contacts"];

// Loop through the fields
foreach (SPField oField in oList.Fields)
{
    // See if this field is not hidden
    if (!oField.Hidden && !oField.ReadOnlyField && oField.Type != SPFieldType.Attachments)
    {
        // Create the label field
        FieldLabel oLabelField = new FieldLabel();
        oLabelField.ControlMode = SPControlMode.New;
        oLabelField.ListId = oList.ID;
        oLabelField.FieldName = oField.InternalName;

        // Create the form field
        FormField oFormField = new FormField();
        oFormField.ControlMode = SPControlMode.New;
        oFormField.ListId = oList.ID;
        oFormField.FieldName = oField.InternalName;

        // Add the table row
        TableRow oRow = new TableRow();
        oTable.Rows.Add(oRow);

        // Add the cells
        TableCell oCellLabel = new TableCell();
        oRow.Cells.Add(oCellLabel);
        TableCell oCellControl = new TableCell();
        oRow.Cells.Add(oCellControl);

        // Add the control to the table cells
        oCellLabel.Controls.Add(oLabelField);
        oCellControl.Controls.Add(oFormField);
   
        // Set the css class of the cell for the SharePoint styles
        oCellLabel.CssClass = "ms-formlabel";
        oCellControl.CssClass = "ms-formbody";
    }
}

// Create the save button
SaveButton oButtonSave = new SaveButton();
oButtonSave.ControlMode = SPControlMode.New;
oButtonSave.ListId = oList.ID;

// Create the row for the save button
TableRow oRowButton = new TableRow();
oTable.Rows.Add(oRowButton);

// Create the cell for the save button
TableCell oCellButton = new TableCell();
oCellButton.ColumnSpan = 2;
oRowButton.Cells.Add(oCellButton);

// Add the table to the web part controls collection
Controls.Add(oTable);

Following is a screen shot of the web part that was rendered with the above code.

Enjoy!!!

Create Your Own Data Entry Form Web Part

Monday, September 24th, 2007

There are many scenarios that I always run into on projects or client sites that we need to create our own data entry forms for lists. Microsoft has really done a lot of work around this in exposing the objects that SharePoint uses so we can reuse these and have the same SharePoint look and feel. This post will show you how to build a data entry web part that uses the same objects that SharePoint does.

There are many discussion on creating web parts and rendering the controls that you create onto web parts. This post will not go into that, but will focus on the objects for a data entry form.

The control that we are dealing with is in the Microsoft.SharePoint.WebControls namespace. There are a couple things that you would want to determine before you actually create and render the control, like if the field is hidden or read only etc… After we determine if this field should be created and displayed we simply create a control called  FormField. Once we create this control you simply set a couple properties and SharePoint will take care of the rest. The 3 main properties are ControlMode, ListId and FieldName. ControlMode tells the control which mode that this form is in (Display, Edit and New). The ListId tells the control which list on the site to hook to and FieldName tells the control which field that this control is attached to in the list. There is a fourth property to set if we are in Edit or Display mode and that is ItemId. If we set ItemId and are in Edit or Display mode, then SharePoint will automatically set the control value to that specific items value in the list. After we have added all of our fields, we can create a SaveButton control (In the same namespace, Microsoft.SharePoint.WebControls). You would also set the ControlMode and ListId properties on the save button to hook that specific button to the list as well. Once you have done all that, all you would need to do is add the controls created to your web parts collection (or however you render your controls inside a web part). Once you have the controls showing up, you can enter and edit data, click Save and SharePoint will take care of determining which list and item to hook to and actually updating the correct list item with the new values. There is also a property on the SaveButton called RedirectUrl. If you do not set this property, once the user hits Save it will automatically redirect the user back to the default list page. If you choose, you can set this property back to the calling page or a different page of your choice and when the user hits Save, they will be redirected back to that page. So you can build web parts that mimic the SharePoint data entry forms without the user ever having to go to the list itself. The other control we are using is the FieldLabel control. The FieldLabel control will render the actual label for that specific field. Below is the full code listing to render the web part.

// Create the table object that we are going to add the rows and cells to for our data entry form
Table oTable = new Table();
oTable.CellPadding = 0;
oTable.CellSpacing = 0;

// Get the site that this web part is running on.
SPWeb oWeb = Microsoft.SharePoint.WebControls.SPControl.GetContextWeb(Context);

// Get the list we are going to work with
SPList oList = oWeb.Lists["Contacts"];

// Loop through the fields
foreach (SPField oField in oList.Fields)
{
    // See if this field is not hidden
    if (!oField.Hidden && !oField.ReadOnlyField && oField.Type != SPFieldType.Attachments)
    {
        // Create the label field
        FieldLabel oLabelField = new FieldLabel();
        oLabelField.ControlMode = SPControlMode.New;
        oLabelField.ListId = oList.ID;
        oLabelField.FieldName = oField.InternalName;

        // Create the form field
        FormField oFormField = new FormField();
        oFormField.ControlMode = SPControlMode.New;
        oFormField.ListId = oList.ID;
        oFormField.FieldName = oField.InternalName;

        // Add the table row
        TableRow oRow = new TableRow();
        oTable.Rows.Add(oRow);

        // Add the cells
        TableCell oCellLabel = new TableCell();
        oRow.Cells.Add(oCellLabel);
        TableCell oCellControl = new TableCell();
        oRow.Cells.Add(oCellControl);

        // Add the control to the table cells
        oCellLabel.Controls.Add(oLabelField);
        oCellControl.Controls.Add(oFormField);
   
        // Set the css class of the cell for the SharePoint styles
        oCellLabel.CssClass = "ms-formlabel";
        oCellControl.CssClass = "ms-formbody";
    }
}

// Create the save button
SaveButton oButtonSave = new SaveButton();
oButtonSave.ControlMode = SPControlMode.New;
oButtonSave.ListId = oList.ID;

// Create the row for the save button
TableRow oRowButton = new TableRow();
oTable.Rows.Add(oRowButton);

// Create the cell for the save button
TableCell oCellButton = new TableCell();
oCellButton.ColumnSpan = 2;
oRowButton.Cells.Add(oCellButton);

// Add the table to the web part controls collection
Controls.Add(oTable);

Following is a screen shot of the web part that was rendered with the above code.

Enjoy!!!