Question

ID    ContributeID   Status

3         150         Pass
2         149         Fail
1         148         Pass

Above is the data in a SharePoint List.

How to retrieve the 'Status' for 'ContributeID = 149' without using 'ID'?

Was it helpful?

Solution

If you know the specific value of a specific field, using a CAML Query is much more direct than looping through all list items. You would end up with code along the lines of:

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

    string queryString = "<Where><Eq>";
    queryString += "<FieldRef Name='ContributeID' />";
    queryString += "<Value Type='Number'>149</Value>"; // you could put any value you are looking for here
    queryString += "</Eq></Where>";

    SPQuery query = new SPQuery();
    query.Query = queryString;

    // getting items using a query will always return a collection object
    SPListItemCollection resultItems = list.GetItems(query);

    if (resultItems.Count > 0)
    {
        // if ContributeID is truly unique, there should be only one item in the collection
        SPListItem singleItem = resultItems[0];
        string status = singleItem["Status"].ToString();
    }
}

See also:

How to retrieve list items

SPList.GetItems(query) method

OTHER TIPS

Get the site collection, then the web, then the list. Then, loop through each item in the list, checking ContributeID against the value you're looking for. There's a sample here: enter link description here

Look for the section starting with, "If you do not know either the GUID or the ID of the list item..."

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top