in

SharePoint Blogs

The Best Place for SharePoint-related Blogs

Ethan's blog

Create Your Own Data Entry Form Web Part

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!!!

Published Sep 24 2007, 08:59 PM by ethan
Filed under: , , ,

Comments

 

bazztrap said:

This is nice!,

September 25, 2007 8:22 AM
 

13 Links Today (2007-09-26) said:

Pingback from  13 Links Today (2007-09-26)

September 26, 2007 10:20 AM
 

valentino said:

Brilliant, well impressed !!!

October 4, 2007 3:36 PM
 

Mark Smith said:

Not being picky but is there any way to make the form fields wider? It may help me on a seporate issue with form fields.

markdsmith@comcast.net

October 5, 2007 5:51 PM
 

David said:

Your code example fails to add the SaveButton to the table cell so that it is rendered. Just thought you might want to update it.

October 8, 2007 9:38 PM
 

Alex Henderson said:

Out of curiosity, how easy is it to take this method and tie in support for attachments - is it even possible to replicate the list item toolbar experience, with the ability to add attachments?

October 10, 2007 5:21 PM
 

Martin Wanerskar said:

Operation is not valid due to the current state of the object

I get the above error when I try to render a list using this method when the list exists on a top level site, and I try to render it on a subsite.

The List exists at the top-level site.

If I call this page from the top-level site then it works.

If I call this page from anywhere else, I get an error message!

Has anyone else experienced this problem, any ideas?

October 15, 2007 3:51 AM
 

George said:

When i'm trying the szmple code i always get an error:

"Object reference not set to an instance of an object"

Any Ideas

October 15, 2007 6:03 PM
 

Michael Stjernstrom said:

Is this solution only applicable when updating one single item in a list or can it be used for multiple updates on a list?

October 18, 2007 8:51 AM
 

Ernie said:

I have a similar need as Michael Stjernstrom.  Is this possible?

October 19, 2007 11:29 AM
 

David said:

Is it possible to run this code with elevated privileges? Which piece of the code would I wrap in the elevated privileges to post the form as the system account?

October 29, 2007 10:19 PM
 

Arun said:

Hi Ethan,

thank you for this nice article. I have a problem. The code is working fine for me. But when I set the RedirectUrl property, the  sharepoint is showing error.

// Create the save button

               SaveButton oButtonSave = new SaveButton();

               oButtonSave.ControlMode = SPControlMode.New;

               oButtonSave.RedirectUrl = "http://localhost:555";

               oButtonSave.ListId = oList.ID;

please help me

November 22, 2007 3:37 AM
 

fredrik said:

I get the following error when I try to do your code with a list located on another site (topsite) ->Operation is not valid due to the current state of the object.

December 13, 2007 6:15 AM
 

padolik said:

Thanx much,

cool stuff.  I had the same issue with SaveButton.

I had to add it to controls and render it separately.

Now it works.

January 26, 2008 6:50 AM
 

Shobha said:

Hi ,

I get this error when is use FieldLabel, FormField control in my User Control Page load event.

I s this controls are only availabe for create child control method ??

'oFormField' is FormField control

'oFormField.Value' threw an exception of type 'System.ArgumentException'

Pls help..

January 29, 2008 1:25 AM
 

Jhon doe said:

Cool Bannanas so cool is it posable for this webpart once it is build to change the colums according to content type

February 1, 2008 7:09 AM
 

I have an error said:

I have an error when exceuting this code.

Here is the exception: Value = 'oFormField.Value' a levé une exception de type 'System.NullReferenceException'. In english:

'oFormField.Value' has rosen a type 'System.NullReferenceException' exception

I,m executing this code in a code Behing page within the Page_load method

February 2, 2008 11:39 PM
 

Adam Cox said:

Hi,

I'm a little stuck in implementing the above solution and was hoping someone would be able to advise...

How is the code above added to a list form (NewForm.aspx for example)?

Do you have a project which contains the code above?

February 5, 2008 6:58 AM
 

aparna said:

Hi ,

I am getting the following error message....let me know in case u have a solution for the following..

-->

The "Class1" Web Part appears to be causing a problem. Request for the permission of type 'Microsoft.SharePoint.Security.SharePointPermission, Microsoft.SharePoint.Security, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' failed.

Thanks in advance

February 11, 2008 7:04 AM
 

Rey said:

How do I add attachments to this ... I  know we can add attachments through List.ADD but I am wondering is there any way that I can add the attachments like all the other fields created in the  dataentry using the above code.

           SPWeb oWeb = Microsoft.SharePoint.WebControls.SPControl.GetContextWeb(Context);

           SPList oList = oWeb.Lists["ListName"];

           SPListItem myitem = oList.Add();

            -----

             myItem.Attachments.Add(Path.GetFileName(FileUpload1.PostedFile.FileName), contents);

           myItem.Update();

using this code I have created my own button to add items but I really would like to get use of the SP SaveButton.  I would greatly appreciate your help!

March 10, 2008 11:41 AM
 

Revathi Jayaraman said:

Never mind ....figured out a way to add attachments along the data entry....here is the code ....AttachmentField is the key element.

        foreach (SPField oField in oList.Fields)

           {

               if (oField.Type == SPFieldType.Attachments)

               {

                   FieldLabel oLabelAttachmentField = new FieldLabel();

                   oLabelAttachmentField.ControlMode = SPControlMode.New;

                   oLabelAttachmentField.ListId = oList.ID;

                   oLabelAttachmentField.FieldName = oField.InternalName;

                   FileUpload1 = new FileUpload();

                   FileUpload1.ID = "FileUpload1";

                   AttachmentsField oAttachmentField = new AttachmentsField();

                   oAttachmentField.ControlMode = SPControlMode.New;

                   oAttachmentField.ListId = oList.ID;

                   oAttachmentField.FieldName = oField.InternalName;

                   oAttachmentField.Controls.Add(FileUpload1);  

                   // Create the row for the attachment

                   TableRow oRowAttachment = new TableRow();

                   oTable.Rows.Add(oRowAttachment);

                   TableCell oCellAttachmentLabel = new TableCell();

                   oRowAttachment.Cells.Add(oCellAttachmentLabel);

                   // Create the cell for the save button

                   oCellAttachmentLabel.Controls.Add(oLabelAttachmentField);

                   oCellAttachmentLabel.CssClass = "ms-formlabel";

                   TableCell oCellAttachment = new TableCell();

                   oRowAttachment.Cells.Add(oCellAttachment);

                   oCellAttachment.Controls.Add(oAttachmentField);

                   oCellAttachment.CssClass = "ms-formbody";

              }

           }

hope this will help somebody!

-Rey

March 11, 2008 11:14 AM
 

Pesi said:

Thank you for the nice article..

Can you please also give a sample code to read, insert and update the data to the database for these controls?

March 26, 2008 5:38 AM
 

MaxGXL Benefits of Glutathione » MaxGXL Glutathione said:

Contrast that to a Blogspot blog , where I can read the entry normally, but I have to click a link to comment. Then I’ m taken to a page just for commenting. Well, what if I want to reference something in the article? It’ s nice to know what I’ m commenting

March 27, 2008 12:24 AM
 

Internet Business Training Program said:

Your post have brought me a greater insight into a deeper level of thinking for me and I just wish to say thanks.

March 29, 2008 3:49 PM
 

Vamshi said:

Thanks for a great post !!!

I have used the above code to create a data entry form that sends xml to a web service to insert the data into a database.

But when I try to prepopulate the form with values for Edit mode, I am able to set values for fields of type text only. The code throws off for datetime fields(below is the code snippet).

FormField oFormField = new FormField();

                       oFormField.ListId = oLst.ID;

                       oFormField.ControlMode = SPControlMode.New;

                       oFormField.FieldName = oField.InternalName;

oFormField.Value = oFormField.Field.GetFieldValue(_fieldValue);//_fieldValue is the string value i fetch from a xml file.

Any Idea how to crack it?

March 31, 2008 11:20 AM
 

hot**** said:

cool!

April 6, 2008 10:23 AM
 

Francois Verbeeck said:

Indeed, invaluable ressource. it saved me a ton of time in a crtical project.

Thanks a lot and also thank you to Revathi Jayaraman for the upload code.

April 7, 2008 7:51 AM
 

Renard said:

Hi all,

This code works great, and thanks a lot for it !!.

But i've got a problem. I've created the possibility to select the list from a dropdownlist. After you selected the list, the code wil generate a nice form for it.

All works fine, except the data isn't entered into the list. When i'm not using the dropdownlist, all works perfect.

Any suggestions?

Greetings. Hans Renard

April 11, 2008 2:22 AM
 

Renard said:

Hi all

I couldn't solve my previous problem. Instead, I removed the dropdownlist and now i'm setting the listname with the properties of the webpart. This works fine.

Greetings. Hans Renard

April 17, 2008 3:47 AM
 

Prasad said:

Hi,

I am also having the same problem as Aparna. When I tried to add the web part it shows the below error message.

"The "Class1" Web Part appears to be causing a problem. Request for the permission of type 'Microsoft.SharePoint.Security.SharePointPermission, Microsoft.SharePoint.Security, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' failed."

Is there any Solution?

Thanks

April 21, 2008 4:37 AM
 

dumb said:

hi  i am a dumb person thanz for the sheet thing

April 25, 2008 3:40 AM
 

dumb said:

hiya  and a idots thanz for help

April 25, 2008 3:42 AM
 

sex master said:

come and *** me

April 25, 2008 3:44 AM
 

lee gay boy said:

i am gay

April 25, 2008 3:48 AM
 

fanny flaps said:

im a ***

April 25, 2008 3:49 AM
 

fanny flaps said:

im a ***

April 25, 2008 3:49 AM
 

michael said:

thanz for help of entry forms

April 25, 2008 3:51 AM
 

ytreyy said:

eyhfghfh

April 25, 2008 3:55 AM
 

jgnfnjgjn said:

dfbhdfnumtyum

April 25, 2008 3:55 AM
 

spas said:

im gay and a mother fucker

April 25, 2008 3:55 AM
 

trgterg said:

etvhrebyet

April 25, 2008 3:56 AM
 

jaskeran bachu said:

hi *** holes

April 25, 2008 9:42 AM
 

gswegzsesegzswegzswgzse said:

fjash zuse gh[wg wga\wsghsweg\

April 28, 2008 5:54 AM
 

lee said:

i love boys

April 28, 2008 5:55 AM
 

lee said:

i like grils

April 28, 2008 5:57 AM
 

lee said:

i like grils

April 28, 2008 5:58 AM
 

lee said:

i like grils

April 28, 2008 5:58 AM
 

lee said:

i like grils

April 28, 2008 5:59 AM
 

reece said:

`edfgbnthlj;pio[';08uyr9p890o/ijm8;u[iyu768oln9kj7iv9obk7ujvkipl76i

April 28, 2008 6:05 AM
 

james said:

i

am

pr

April 28, 2008 6:06 AM
 

james said:

i

am

pr

April 28, 2008 6:06 AM
 

james said:

the only letters i no of the alferbet is KFC

April 28, 2008 6:07 AM
 

james said:

i

am

propa

gay

April 28, 2008 6:07 AM
 

james said:

i

am

propa

gay

April 28, 2008 6:07 AM
 

chuks said:

what the ***

April 28, 2008 6:08 AM
 

gshbgf said:

shfyydfr

April 28, 2008 6:09 AM
 

jyerhutdryjr said:

yjtrjytejutyrehuy

April 28, 2008 6:09 AM
 

ryuhnfxdhgbgd said:

h6gnjfdygfmthnjryfmyl

April 28, 2008 6:09 AM
 

fgmjhjfnhm said:

qh hgmkhgjkhnhtg

April 28, 2008 6:10 AM
 

hhhhhhhhhhhhhhhh said:

hhfbyughjnhfjn

April 28, 2008 6:10 AM
 

cerebral palsy cause said:

Some health professionals believe that the most commonly used medications to treat CP (diazepam[ such as Valium], baclofen[ Lioresal], and dantrolene[ Dantrium]) should not be given to growing children. They are concerned that the side effects from these

May 11, 2008 5:20 PM
 

superchinois said:

If I put two of those webparts I got validation group problems.

Any way to solve them?

July 7, 2008 4:14 AM
 

EC Ogtip said:

Anybody here had ever use javascript to get the value of

a PublishingWebControls:RichHtmlField on a page?

I am doing a document.getElementsByName("EvaluateRichTextField") which is returning me an object. How do you get the valud of this control?

thanks

September 11, 2008 3:41 AM
 

Blog del CIIN said:

Una vez más, os presentamos el recopilatorio (con periodicidad mensual) de recursos interesantes que

September 23, 2008 4:43 PM
 

WSS 3.0 & MOSS: Recopilatorio de enlaces interesantes (XXI)! « Pasi??n por la tecnolog??a… said:

Pingback from  WSS 3.0 & MOSS: Recopilatorio de enlaces interesantes (XXI)! « Pasi??n por la tecnolog??a…

September 23, 2008 4:48 PM
 

N said:

HI EC Ogtip

document.getElementsByName("EvaluateRichTextField").value should work for you.

September 30, 2008 1:36 PM

Leave a Comment

(required )  
(optional )
(required )  
Add

Need SharePoint Training? Attend a SharePoint Bootcamp!

Posts (c) their respective authors. Everything else (c) 2007 SharePoint Experts