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("
");
        }
    }
}