0

I am trying to get a specific item from sharepoint list, representing the username of the current logged in user. The list has a column called UserName, which has values like: i:0#.f|sql_membership|Jacky

I am building a CAML query in C#, to get the row where current logged in user = that column. My code looks like this:

  SPUser user = web.CurrentUser;
  string userName = user.LoginName;
  query.Query = "<View><Query><Where><Eq><Field Name= 'UserName'/><Value Type='Text'>" + userName + "</Value></Eq></Where></View></Query>";
   SPListItemCollection items = list.GetItems(query);
   SPListItem item = items[0];

The problem, is that it brings the first row with ID =1, which has the value of: i:0#.f|sql_membership|Edward while it should bring: i:0#.f|sql_membership|Jacky according to the value the userName variable which has my username

How do I solve this?

  • try removing the view and query nodes from the caml xml – Jaime Nov 17 '16 at 16:22
  • @Jaime , now it stopped bringing any items at all. – Jacky Nov 17 '16 at 16:32
2
query.Query = @"<Where><Eq><FieldRef Name='UserName' /><Value Type='Integer'><UserID Type='Integer' /></Value></Eq></Where>";
SPListItemCollection items = list.GetItems(query);
if (items.Count > 0)
{
    SPListItem item = items[0];
}
1

You have to escape the special characters in XML. So you need to pass the value under CDATA object. Something like:

<Contains><FieldRef Name='Title' /><Value Type='Text'><![CDATA[{0}]]>  </Value</Contains>
0

Just use following Query:

<Where>
  <Eq>
    <FieldRef Name="UserName" />
    <Value Type="Integer">
      <UserID />
    </Value>
  </Eq>
</Where>

So

query.Query = "<Where><Eq><FieldRef Name='UserName' /><Value Type='Integer'><UserID /></Value></Eq></Where>";

<UserID /> will get the current user ID.

The following will also work:

var currentUserId = web.CurrentUser.ID;
query.Query = "<Where><Eq><FieldRef Name='UserName' LookupId='True' /><Value Type='Lookup'>" + currentUserId + "</Value></Eq></Where>";
  • Hi Arsalan. How will UserID check for i:0#.f|sql_membership|Jacky ????? – Jacky Nov 17 '16 at 17:18
  • It's still modifying i:0#.f|sql_membership|Edward instead of my username. – Jacky Nov 17 '16 at 17:27
  • Do you always need current login user or other user than logged in user ? – Monica Jagani Nov 18 '16 at 6:17
  • @MonicaJagani I need the logged in user always – Jacky Nov 18 '16 at 8:05
  • Above mentioned solution should work of taking the web.CurrentUser.ID and passing to CAML query. – Monica Jagani Nov 18 '16 at 8:07

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.