0

I am trying to get some information from a SPListItem by the following code:

 SPList list = SPContext.Current.Web.Lists[listName];
 SPView spview = list.Views["All Items"];
 SPQuery query = new SPQuery();
 query.Query = string.Concat(
                         "<Where><Eq>",
                                         "<FieldRef Name='ID'/>",
                                         "<Value Type='Integer'>" + the_Item_ID + "</Value>",
                                      "</Eq></Where>");

            foreach (string viewField in spview.ViewFields)
            {
                query.ViewFields += "<FieldRef Name='" + viewField + "' />";
            }
            query.ViewAttributes = "Scope=\"Recursive\"";
            query.ViewFieldsOnly = true;

SPListItemCollection items list.GetItems(query);
SPListItem item = items[0];
//string title  = Convert.ToString(item["Title"]);// <-Fail, i don't know why
string title = Convert.ToString(item["LinkTitle"]); //<- pass

Guid id = item.UniqueId;//Fail, i don't know why

Can anyone tell me how to get the uniqueid of splistitem?

0

Try below code:

SPList list = SPContext.Current.Web.Lists[listName]; 
SPQuery query = new SPQuery();
query.Query = string.Concat(
                 "<Where><Eq>",
                                 "<FieldRef Name='ID'/>",
                                 "<Value Type='Integer'>" + the_Item_ID + "</Value>",
                              "</Eq></Where>");

//specify the field names that you want to use later on in the code
query.ViewFields = "<FieldRef Name='Title' /><FieldRef Name='LinkTitle' /><FieldRef Name='UniqueId' /><FieldRef Name='ID' />";

query.ViewAttributes = "Scope=\"Recursive\"";
query.ViewFieldsOnly = true;

SPListItemCollection items list.GetItems(query);
SPListItem item = items[0];
string title  = Convert.ToString(item["Title"]);
string linkTitle = Convert.ToString(item["LinkTitle"]); 

Guid id = item.UniqueId;

By default, the All Items view has the LinkTitle field and not Title field. So, your code failed as it got the view fields from the all items view. To get the view fields that you want, you need to specify them as in the above code snippet.

0

If you simply want yo retrieve an item from its ID (as your current CAML query suggests), you can simply use the call to list.GetItemById. That way your SPListItem will ne full populated, and I'm sure UniqueId will ne OK.

0

You should remove this line

    query.ViewFieldsOnly = true;

This option prohibits access to columns like UniqueId.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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