Thursday, February 24, 2011

Webpart to render New Form dynamically for a list item

To generate/render a new form in a webpart dynamically to create/add a list item. Where the field name, type of each field will be fetched and rendered respectively. It holds the full control on all the properties of a column.
//Create the table object that we are going to add the rows and cells to for our data entry form
Table tbl = new Table();
tbl.CellPadding = 0;
tbl.CellSpacing = 0;

// Get the site that this web part is running on.
SPWeb spWeb = SPContext.Current.Web;

// Get the list we are going to work with
SPList spList = spWeb.Lists["MyList"];

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

// Create the form field
FormField formField = new FormField();
formField.ControlMode = SPControlMode.New;
formField.ListId = spList.ID;
formField.FieldName = spField.InternalName;

// Add the table row
TableRow tblRow = new TableRow();
tbl.Rows.Add(tblRow);

// Add the cells
TableCell tblLabelCell = new TableCell();
tblRow.Cells.Add(tblLabelCell);
TableCell tblControlCell = new TableCell();
tblRow.Cells.Add(tblControlCell);

// Add the control to the table cells
tblLabelCell.Controls.Add(fieldLabel);
tblControlCell.Controls.Add(formField);

// Set the css class of the cell for the SharePoint styles
tblLabelCell.CssClass = "ms-formlabel";
tblControlCell.CssClass = "ms-formbody";
}
}

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

// Create the row for the save button
TableRow tblButtonRow = new TableRow();
// Create the cell for the save button
TableCell tblButtonCell = new TableCell();

tblButtonCell.ColumnSpan = 2;
tblButtonRow.Cells.Add(tblButtonCell);
tbl.Rows.Add(tblButtonRow);

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