Wednesday, January 26, 2011

SPFieldUser is not persistent during postback

If you are using a custom listform and refering to a field of type SPFieldUser. The field tend to loose the content (users) during postback. Some times not easily detected because it will keep the viewstate sometimes.

This has been seen on versions 2007 and 2010.

The fix is relatively simple, by putting the contents into the viewstate in code.

Example:

In the listform.aspx

<SharePoint:FormField runat="server" id="Fld_Present" ControlMode="Edit" FieldName="Present" />

Snippets from codebehind

protected FormField Fld_Present; // Define the field in codebehind

// Define a private String for holding the value during postbacks

 

private String Present

{

    get

    {

        object obj = ViewState["Present"];

        return (obj == null) ? String.Empty : (String)obj;

    }

    set

    {

        ViewState["Present"] = value;

    }

}

 

protected override void CreateChildControls()

        {

            base.CreateChildControls();

 

            if (Fld_Attendees.Value.ToString() != "")

                this.Attendees = Fld_Attendees.Value.ToString();

            else

                Fld_Attendees.Value = new SPFieldUserValueCollection(SPContext.Current.Web, this.Attendees);

 

To keep values when the user field is edited, also add some code before postbacks that is defined in codebehind:

 

if (Fld_Attendees.Value.ToString() != "")

                    this.Attendees = Fld_Attendees.Value.ToString();

 

No comments: