SPQuery Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index

sharepoint.stackexchange https://sharepoint.stackexchange.com/questions/196009

  •  09-12-2020
  •  | 
  •  

Question

I need to process a query like this

    <Where> 
      <In>
        <FieldRef Name='AgentId' />
        <Values>
           <Value Type='Text'>7727839</Value>
          <Value Type='Text'>222456</Value>
    <Value Type='Text'>0922456</Value>
...


        </Values>
          </In>     
    </Where>

could you please help me to correct my code :

 List<string> conditionsFS = new List<string>();
 private const string CAMLVALUEAGENTID = "<Value Type='Text'>{0}</Value>";
  private const string CAMLWHEREAGENTID = "<Where><In><FieldRef Name='AgentId'/><Values>{0}</Values></In></Where>";
 string conditionFS = string.Format(CAMLVALUEAGENTID, agentId);

                            if (!conditionsFS.Contains(conditionFS))
                            {
                                conditionsFS.Add(conditionFS);
                            }

 string whereFS = string.Format(CAMLWHEREAGENTID, this.BuildConditionsIN(conditionsFS));

 private string BuildConditionsIN(List<string> conditions)
        {
            string conditionStatement = string.Empty;

            if (conditions.Count > 0)
            {
                conditionStatement = "{0}";

                for (int items = conditions.Count; items > 0; items--)
                {
                    string formatedCondition = string.Empty;

                        formatedCondition = conditions[items];


                    conditionStatement = string.Format(conditionStatement, formatedCondition);
                }

            }

            return conditionStatement;
        }

this is the error message from line : " conditionStatement = string.Format(conditionStatement, formatedCondition);" : Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index

Was it helpful?

Solution

Your for cycle is going in reverse order through the conditions list. In this case you are trying to reference wrong index of the list. In C# lists and arrays are zero-based.

Example. If your conditions list has 3 items, in first step of for loop you are trying to get conditions[3], witch is out of bound.

You should do for loop in normal order like this:

for (int items = 0; items < conditions.Count; items++) 
{
...
}

or fix items value

for (int items = conditions.Count - 1 ; items >= 0; items--)
{
...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top