1

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;
    }

1 Answer 1

2

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;
1
  • Thank you very much, this is exactly what I was looking for. I have another question regarding my GetListItemIDFromQueryParameter() function. My issue is that it only handles one selected file. I'm trying to create a foreach loop so that it could return a string with all the IDs, separated with space. I put the code in edited thread. I should be able to write it once I know how to get the ammount of selected files and a reference to a selected file.
    – Qya
    Commented Aug 23, 2017 at 14:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.