in SharePoint 2010

SharePoint 2010 Client OM: Type Casting Field instances to Field Type instances

If you are using Client Object Model to create Fields, you will be working with the Field class:

private static void AddFieldsToProjectsList()
{
    String fldDescriptionXml = String.Format(FieldXml,
                                            "<guid>",
                                            "Text",
                                            "Description",
                                            "Description",
                                            "TRUE",
                                            "TRUE",
                                            "TRUE",
                                            "TRUE");

    String fldDueDateXml = String.Format(FieldXml,
                "<guid>",
                "DateTime",
                "DueDate",
                "Due Date",
                "TRUE",
                "TRUE",
                "TRUE",
                "TRUE");


    using (ClientContext spContext = new ClientContext(_siteUrl))
    {
        spWeb = spContext.Web;

        List lstProjects = spWeb.Lists.GetByTitle("Projects");

        Field fldDescription = lstProjects
            .Fields
            .AddFieldAsXml(fldDescriptionXml,
                            true,
                            AddFieldOptions.AddToDefaultContentType);

        Field fldDueDate = lstProjects
            .Fields
            .AddFieldAsXml(fldDueDateXml,
                            true,
                            AddFieldOptions.AddToDefaultContentType);

        spContext.ExecuteQuery();
    }
}

As you can see in the above code sample, I am adding a DateTime field. So, what if I have to change the field’s DisplayFormat to Date only?

If you try to cast the Field object to FieldDateTime object, you will get an error:

Unable to cast object of type ‘Microsoft.SharePoint.Client.Field’ to type ‘Microsoft.SharePoint.Client.<field-type>’

image

So, how do we cast then?

You should use SPContext.CastTo method to cast a specified client object to its derived type.

Below is the right way to cast a Field object to FieldDateTime object:

FieldDateTime fldDateField = spContext.CastTo<FieldDateTime>(fldDueDate);
fldDateField.DisplayFormat = DateTimeFieldFormatType.DateOnly;
fldDateField.UpdateAndPushChanges(true);

Write a Comment

Comment

Time limit is exhausted. Please reload the CAPTCHA.