When you’re developing custom code for SharePoint, sometimes you’ll have a situation where you’re dynamically adding form field controls to your control or WebPart and the form context will not be automatically picked up by the controls. If you’re using them outside a new, display or edit form for example.
It’s relatively simple to force the control(s) to the desired context but there’s something you should be aware of.
Take a look the following code:
private void SetFormFieldContext(FieldMetadata formfield, Guid listId, int itemId) { formfield.ListId = listId; formfield.ControlMode = ControlMode; // Get the SPContext object based on the current web and specified list id and item id. SPContext context = SPContext.GetContext(HttpContext.Current, itemId < 0 ? 0 : itemId, listId, SPContext.Current.Web); formfield.RenderContext = context; formfield.ItemContext = context; if (ControlMode == SPControlMode.Display || ControlMode == SPControlMode.Edit) { formfield.ItemId = itemId; } } |
The important part is to manually set the form field’s ListId property, as this is not updated after setting RenderContext or ItemContext as you might expect.
The same applies to the ItemId property.