Dynamically creating form controls in SharePoint
Posted by zieglers on April 8, 2010
While doing SharePoint development, occasionally we find ourselves in situations that we need to create controls dynamically based on some user selection, querystring parameter, … etc.
Here I provide you a code snippet which you can use in custom SharePoint application pages or web parts. This code is basically,
- creating an HTML table
- looping thru some fields (those can be SPListItem fields or any collection you want based on which you’ll generate controls dynamically)
- creating a SPContext based on item
- creating FieldLabel and FormField objects using SPContext (This allows controls to be created based on their rendering and item context. For example, say Title field is string, textbox control will be created or Start Date is DateTime, then textbox with calendar control will be created.) This means you don’t need to worry about which type of control you need to create.
- adding FieldLabel and FormField to table rows.
- finally adding constructed table to some other control before rendering, say to a panel.
You can download code snippet, CreateControls method, here: Creating Dynamic SharePoint Form Controls