Question

I'm trying to write a SharePoint add-in which has a part that has to assign the name of a selected file in "Documents" list to a string called title.

protected void Page_Load(object sender, EventArgs e)
{

    var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

    int listItemID;

    listItemID = GetListItemIDFromQueryParameter();

    using (var clientContext = spContext.CreateUserClientContextForSPHost())
    {
        clientContext.Load(clientContext.Web,
        web => web.Title,
        web => web.CurrentUser,
        web => web.Lists);

        List doclist = clientContext.Web.Lists.GetByTitle("Documents");
        Microsoft.SharePoint.Client.ListItem item = doclist.GetItemById(listItemID);

        string title = item.File.Title;
    }
}

Function GetListItemIDFromQueryParametr(); works like intended - it returns an ID int value of the selected file. I want to get the file's name by that ID. The following code returns an error -

Microsoft.SharePoint.Client.PropertyOrFieldNotInitializedException: 'The property or field 'Title' has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.'

I am now trying to figure out how to initialize that field, but so far I haven't found anything that would help me. Any clues would be much appreciated.

/// also adding the GetMyItemIDFromQueryParameter() function

    private int GetListItemIDFromQueryParameter()
    {
        int result;
        Int32.TryParse(Request.QueryString["SPListItemId"], out result);
        return result;
    }
Was it helpful?

Solution

In CSOM, you need to explicitly load the item and the properties that you need.

So, modify the code as below:

List doclist = clientContext.Web.Lists.GetByTitle("Documents");
Microsoft.SharePoint.Client.ListItem item = doclist.GetItemById(listItemID);

context.Load(item, i => i.File);
context.ExecuteQuery();

string title = item.File.Title;
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top