Sharepoint list form generator

Today I am going to show you how to generate a list form dynamically as soon as you select the list name you can see the form generated for you with file upload field (attachment). I also know that there is  an excellent solution Sharepoint Form Generator developed by Alon Havivi, but still I want to share with you, so that for some one the code may be helpful as a whole or part of it

No problem whether your list contains 1 field or 100 fields, code will  generate all the ‘n’ no.of fields with file upload field (attachment) contained in the list. It loops through all the input fields and creates at runtime.

All you have to do is, open visual studio 2005/2008 create a new project using webpart template use the code from WebPart1.cs and FormGeneratorToolPart.cs build the project, place the .dll file in GAC or site bin directory, add the necessary safe control tag in Web.config file, import the webpart in to gallery, and add the same on to your site, after adding the webpart in your site you have to select the list name from the webpart properties, so that you can see the generated form similar to the form as in NewForm.aspx

Select the list name from the list of lists

Select the list name from the list of lists

List form generated

List form generated

Download the complete source code (Please Note: Code cannot be viewed properly on the web page, so please use the below links to view the code or for downloading)

WebPart1.cs
FormGeneratorToolPart.cs

WebPart1.cs

using System;
using System.Web;
using System.IO;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using System.Web.UI.WebControls;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

namespace FormGenerator
{
    [Guid("93612d52-737c-4e83-83c3-a228910e87a3")]
    public class FormGenerator : Microsoft.SharePoint.WebPartPages.WebPart
    {
        Table oFormTable;
        FileUpload oFormFileUpload;
        FieldLabel oFormLabelField;
        FormField oFormField;
        Button oFormButtonSubmit;
        Label oFormLabelMessage;

        SPList oFormList;

        private string _FormList = string.Empty;

        string qstitle = string.Empty;
        string qsmission = string.Empty;

        public string FormList
        {
            get { return _FormList; }
            set { _FormList = value; }
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            oFormTable = new Table();
            oFormTable.CellPadding = 0;
            oFormTable.CellSpacing = 0;            

            oFormLabelMessage = new Label();
            oFormLabelMessage.ID = "lbl_message";
            oFormLabelMessage.CssClass = "ms-formvalidation";
            this.Controls.Add(oFormLabelMessage);

            //Generate Form
            GenerateFormList();
        }

        private void GenerateFormList()
        {
            SPWeb oWeb = Microsoft.SharePoint.WebControls.SPControl.GetContextWeb(Context);
            if (FormList != "")
            {
                try
                {
                    oFormList = oWeb.Lists[FormList];
                    foreach (SPField oField in oFormList.Fields)
                    {
                        if (oField.Type == SPFieldType.Attachments)
                        {
                            FieldLabel oLabelAttachmentField = new FieldLabel();
                            oLabelAttachmentField.ControlMode = SPControlMode.New;
                            oLabelAttachmentField.ListId = oFormList.ID;
                            oLabelAttachmentField.FieldName = oField.InternalName;

                            oFormFileUpload = new FileUpload();
                            oFormFileUpload.ID = "FileUpload";

                            AttachmentsField oAttachmentField = new AttachmentsField();
                            oAttachmentField.ControlMode = SPControlMode.New;
                            oAttachmentField.ListId = oFormList.ID;
                            oAttachmentField.FieldName = oField.InternalName;
                            oAttachmentField.Controls.Add(oFormFileUpload);
                            oAttachmentField.ID = "Control_" + oField.InternalName;

                            TableRow oRowAttachment = new TableRow();
                            oFormTable.Rows.Add(oRowAttachment);
                            TableCell oCellAttachmentLabel = new TableCell();
                            oRowAttachment.Cells.Add(oCellAttachmentLabel);

                            oCellAttachmentLabel.Controls.Add(oLabelAttachmentField);
                            oCellAttachmentLabel.CssClass = "ms-formlabel";
                            TableCell oCellAttachment = new TableCell();
                            oRowAttachment.Cells.Add(oCellAttachment);
                            oCellAttachment.Controls.Add(oAttachmentField);
                            oCellAttachment.CssClass = "ms-formbody";
                        }
                    }

                    // Loop through all the fields in the list
                    foreach (SPField oField in oFormList.Fields)
                    {
                        // Avoid Hidden, Read Only, Attachments field
                        if (!oField.Hidden && !oField.ReadOnlyField && oField.Type != SPFieldType.Attachments)
                        {
                            oFormLabelField = new FieldLabel();
                            oFormLabelField.ControlMode = SPControlMode.New;
                            oFormLabelField.ListId = oFormList.ID;
                            oFormLabelField.FieldName = oField.InternalName;

                            oFormField = new FormField();
                            oFormField.ControlMode = SPControlMode.New;
                            oFormField.ListId = oFormList.ID;
                            oFormField.FieldName = oField.InternalName;
                            oFormField.ID = "Control_" + oField.InternalName;

                            TableRow oRow = new TableRow();
                            oFormTable.Rows.Add(oRow);

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

                            oCellLabel.Controls.Add(oFormLabelField);
                            oCellControl.Controls.Add(oFormField);

                            oCellLabel.CssClass = "ms-formlabel";
                            oCellControl.CssClass = "ms-formbody";
                        }
                    }

                    //Create ASP.Net button
                    oFormButtonSubmit = new Button();
                    oFormButtonSubmit.ID = "btn_submit";
                    oFormButtonSubmit.Text = "OK";
                    oFormButtonSubmit.CssClass = "ms-ButtonHeightWidth";
                    oFormButtonSubmit.Click += new EventHandler(oFormButtonSubmit_Click);
                    this.Controls.Add(oFormButtonSubmit);

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

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

                    Controls.Add(oFormTable);
                }
                catch (Exception ex)
                {
                    Page.Response.Write(ex.ToString());
                }
            }
            else
            {
                Page.Response.Write("Select valid List from webpart properties");
            }
        }

        void oFormButtonSubmit_Click(object sender, EventArgs e)
        {
            SPSite mySite = SPControl.GetContextSite(Context);
            SPWeb myWeb = SPControl.GetContextWeb(Context);
            SPList myList = myWeb.Lists[FormList];
            SPListItem myItem = myList.Items.Add();

            //Validating the controls
            foreach (SPField sField in myList.Fields)
            {
                if (sField.Required == true)
                {
                    string oControl = "Control_" + sField.InternalName.ToString();
                    Control oFieldControl = this.FindControl(oControl);
                    FormField sFormField = (FormField)oFieldControl;
                    if ((sFormField.Value) == null || (sFormField.Value.ToString()) == "")
                    {
                        oFormLabelMessage.Visible = true;
                        oFormLabelMessage.Text = "* indicates required fields";
                        return;
                    }
                }
            }
            foreach (SPField oField in myList.Fields)
            {
                string oFieldID = "Control_" + oField.InternalName;
                Control sFieldControl = this.FindControl(oFieldID);
                if (sFieldControl != null)
                {
                    if (oField.Type != SPFieldType.Attachments)
                    {
                        FormField sFormField = (FormField)sFieldControl;
                        myItem[oField.InternalName] = sFormField.Value;
                    }
                    else
                    {
                        AttachmentsField sAttachmentField = (AttachmentsField)sFieldControl;
                        FileUpload oFileControl = (FileUpload)sAttachmentField.FindControl("FileUpload");
                        if (oFileControl != null)
                        {
                            try
                            {
                                HttpPostedFile oPostedFile = oFileControl.PostedFile;
                                string oFileName = Path.GetFileName(oPostedFile.FileName);
                                if (oPostedFile.ContentLength > 0)
                                {
                                    Stream oInputStream = oPostedFile.InputStream;
                                    byte[] oBT = new byte[oPostedFile.InputStream.Length];
                                    oPostedFile.InputStream.Seek(0, SeekOrigin.Begin);
                                    oPostedFile.InputStream.Read(oBT, 0, oBT.Length);
                                    myItem.Attachments.Add(oFileName, oBT);
                                }
                            }
                            catch (Exception ex)
                            {
                                oFormLabelMessage.Visible = true;
                                oFormLabelMessage.Text = ex.ToString();
                            }
                        }
                    }
                }
                myWeb.AllowUnsafeUpdates = true;
                myItem.Update();
                myWeb.AllowUnsafeUpdates = false;
                oFormLabelMessage.Visible = true;
                oFormLabelMessage.Text = "Record updated";
            }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            if (FormList != "")
            {
                writer.Write("
“); oFormLabelMessage.RenderControl(writer); writer.Write(“
");
                writer.Write("
");
                writer.Write("

“); writer.Write(”

“); oFormTable.RenderControl(writer); writer.Write(“
“); oFormButtonSubmit.RenderControl(writer); writer.Write(“
");
            }
            else
            {
                oFormLabelMessage.RenderControl(writer);
            }
        }

        public override ToolPart[] GetToolParts()
        {
            ToolPart[] allToolParts = new ToolPart[3];
            WebPartToolPart standardToolParts = new WebPartToolPart();
            CustomPropertyToolPart customToolParts = new CustomPropertyToolPart();
            allToolParts[0] = standardToolParts;
            allToolParts[1] = customToolParts;
            allToolParts[2] = new FormGeneratorToolPart();
            return allToolParts;
        }
    }
}

FormGeneratorToolPart.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;

namespace FormGenerator
{
    class FormGeneratorToolPart: Microsoft.SharePoint.WebPartPages.ToolPart
    {
        FormGenerator oFG;
        Panel oToolPartPanel;
        DropDownList oDDLListProvider;

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            oToolPartPanel = new Panel();
            Controls.Add(oToolPartPanel);

            oDDLListProvider = new DropDownList();                      
            oToolPartPanel.Controls.Add(oDDLListProvider);

            PopulateProviderList();
        }

        private void PopulateProviderList()
        {
            SPListCollection myListCol = SPContext.Current.Web.Lists;
            oDDLListProvider.AppendDataBoundItems = true;            
            foreach (SPList myList in myListCol)
            {
                ListItem myListItem = new ListItem(myList.Title, myList.Title);
                oFG = (FormGenerator)this.ParentToolPane.SelectedWebPart;
                if (oFG.FormList == myList.Title)
                    myListItem.Selected = true;
                oDDLListProvider.Items.Add(myListItem);
            }
        }

        public override void ApplyChanges()
        {
            base.ApplyChanges();
            oFG.FormList = oDDLListProvider.SelectedValue;
        }

        public override void SyncChanges()
        {
            base.SyncChanges();
            oDDLListProvider.SelectedValue = oFG.FormList.ToString();
        }

        protected override void RenderToolPart(System.Web.UI.HtmlTextWriter output)
        {            
            output.Write("List Name Lookup:");
            output.Write("

");
            oDDLListProvider.RenderControl(output);
            output.Write("
");
        }
    }
}

21 Responses to “Sharepoint list form generator”

  1. Venkatesh Suagana on November 9th, 2009 at 5:57 am

    Hi,

    If I want to eleminate some columns from list, means In my list there is items like
    EmployeeName
    ID
    Dept
    Designation
    If I want to hide Designation from the form, how can I do that. And is it possible to display the perticular content type from the list instead of whole items in the list.

  2. @ Ventakesh: Add the condition !oField.InternalName==”Designation” in IF condition on line number 101 in WebPart1.cs file

  3. Venkatesh Suagana on November 9th, 2009 at 6:39 am

    Is it possible to diplay the form generator from the particular content type from the list instead of modification the code again and again for every list.

  4. Hi,

    Is it possible to generate a display form instead of edit form?

  5. @ Sreenivas: If you are looking for generating custom display form please follow the link http://www.hezser.de/blog/archive/2007/06/18/display-a-single-listitem.aspx

  6. It is very good ..
    But how to do add custom list names dynamically in webpart list .
    I mean .. custom list have empId, Name, phone no columns –> i want that list names bind dynamically to webpart labels (with out hard coding)

  7. @ Rajender: In the image http://www.fivenumber.com/wp-content/uploads/2009/10/1.gif you can see the input field label’s (Title, Employee name, Designation) were not hard coded in the code, the label’s too generated at run time, so no need to worry about hard coding the form field label’s the code take cares of than
    FYI: In the second foreach loop (from line no:108 to 112) the below lines are responsible for generating the form field label’s at run time

    oFormLabelField = new FieldLabel();
    oFormLabelField.ControlMode = SPControlMode.New;
    oFormLabelField.ListId = oFormList.ID;
    oFormLabelField.FieldName = oField.InternalName;

  8. Thank you sfor ur fast reply..
    after adding the webpart in site , where i can find the webpart properties.. please help in this……urgent

  9. its working fine.. thank u

  10. @ Rajender: It’s my pleasure, glad to hear that it’s working fine and thanks for looking into the post 🙂

  11. I tried your code but the button click event is never fired. Could it be because i’m do not derived from webpart but from webcontrol?

  12. @ Sylvain: Can you please send your code through contact form http://www.fivenumber.com/contact/ so that it will be helpful for me to find out the issue, thank for looking to this post

  13. Hi,
    if I put this webpart in an anonymous site, MOSS ask me for username and password and I want to avoid this. With debug I get the following error in WebPart1.cs line 147 (Controls.Add(oFormTable)): “Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack”.
    I tried putting the code inside a SPSecurity.RunWithElevatedPrivileges, but no luck. Any guess?
    Thank you

  14. Hi,

    Thanks for this post.I able to generate a list form dynamically.I m trying to get EditForm in the manner by passing list id.All the column gets generated correctly using the ListID expect the Date column.Is there anything special i need to do to generate a Date column

    Thanks,
    Anu

  15. @ Anu: There is no problem with date column generation, the generates with out any issues, have you modified the code in any line? please confirm

  16. i didnot change the code.It is not in the new form but in the edit form which i am creating like new form except assigning values to field based on list id .
    It works for normal text and doesn’t load values for “lookup” field and “datetime” field.
    For lookup it says:NameError: Value does not fall within the expected range.Stack: at Microsoft.SharePoint.SPFieldLookupValue.ParseLookupId(String fieldValue)
    at Microsoft.SharePoint.SPFieldLookupValue..ctor(String fieldValue)

    It because I m trying to store in FORMFIELD Control.please advice

    Thanks,
    Anu

  17. Hi, could not get this to work, unable to import the webpart, could you please assist with further guide

  18. Hi,

    Thanks for share your code!

    We want validation for formfield like (Number/ currency/ integer/ Datetimecontrol) in sharepoint form generator webpart. Please let me know how we implement custom validation for formfield

    Thanks,
    Nandy

    Please let me know

  19. @ Nandy: You can create a regular expression validation control, then based on form field id hook up the validation control the the form field, let me know if you need more details, thanks for looking in to the post, Good Luck

  20. I have a requirement where in a dropdown has all content types and based on the content type selected the controls are loaded. Dropdown postback causes all dynamically created controls to vanish…please help…

  21. @ Swarna: Sorry for the delay in responding, please post your code or send through contact form of this website, so that it will be easy to identify the problem, thanks for looking into the post.

Leave a Reply