0

I've got a list with 2 columns col1 and col2. I wrote a CAML query and I want to print the value from the second column corresponding to the value from the first

using (SPSite site = new SPSite(administrationUrl))
{
    using (SPWeb web = site.OpenWeb())
    {
        SPList list = web.Lists["list"];

        SPQuery query = new SPQuery();
        query.Query = "<Where>" +
                        "<Eq>" +
                            "<FieldRef Name='col1'>" + "<Value Type='Text'>Test</Value>" +
                        "</Eq>" +
                      "</Where>";
        SPListItemCollection collection = list.GetItems(query);
        foreach (SPListItem item in collection)
        {
            Console.WriteLine(item["col2"]);
        }
    }
}

I tried, but it doesn't work.

0

If you create columns "col1" and "col2", the columns internal names will "_x0063_ol1" and "_x0063_ol2".

Modify the code as below:

using (SPSite site = new SPSite(administrationUrl))
{
    using (SPWeb web = site.OpenWeb())
    {
        SPList list = web.Lists["list"];

        SPQuery query = new SPQuery();
        query.Query = "<Where>" +
                        "<Eq>" +
                            "<FieldRef Name='_x0063_ol1'/>" + "<Value Type='Text'>Test</Value>" +
                        "</Eq>" +
                      "</Where>";
        SPListItemCollection collection = list.GetItems(query);
        foreach (SPListItem item in collection)
        {
            Console.WriteLine(item["_x0063_ol2"]);
        }
    }
}   

If you use SharePoint Online, we need use CSOM code to achieve it.

string siteUrl = "https://test.sharepoint.com/sites/lz";
var login = "lz@test.onmicrosoft.com";
var password = "xx";

ClientContext ctx = new ClientContext(siteUrl);
var securePassword = new SecureString();
foreach (char c in password.ToCharArray()) securePassword.AppendChar(c);
ctx.Credentials = new SharePointOnlineCredentials(login, securePassword);


List oList = ctx.Web.Lists.GetByTitle("list");

CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = "<View><Query><Where><Eq><FieldRef Name='_x0063_ol1'/><Value Type='Text'>test</Value></Eq></Where></Query></View>";

ListItemCollection collListItem = oList.GetItems(camlQuery);
ctx.Load(collListItem);
ctx.ExecuteQuery();
foreach (ListItem oListItem in collListItem)
{
    Console.WriteLine(oListItem["_x0063_ol2"]);
} 

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.