SPList Item get value - ArgumentException

10.5k views Asked by At

I have an SPListItem and I have an array of column names. When I try to access the SPListItem values using the code below:

for(int i=0;i<arrColName.length;i++)
{
    string tempValue =  item[arrColName[i]].ToString();
    // Works fine in case the the specific column in the list item is not null
    // Argument exception - Values does not fall witing expected range
    // exception in case the value //is null
}
5

There are 5 answers

0
Zigu On

Sharepoint Lists aren't stored as a array with a static size.

You have to use the built in sharepoint iterator to go through each element

For example:

SPList checklist = //Some initiliaztion

foreach (SPListItem item in checklist.Items){
     //work
}

This will do work on each item in your SPlist

Edit: Wrong advice, I didn't see the code until after the edit.

Maybe try a cast?

(String)item[colname]
0
Jamil On

I had a similar situation with custom cascade field (or column). I did it following way and it seemed to work for the custom field types.

item.Properties["Country"] = "Mexico"; // custom field
item.Properties["nCity"] = "Cancun"; // custom field
item["Document Descriptions"] = "Test document description.";

Note: I added item.Properties for the custom columns. No need to add properties for built in field type (else they don't work).

0
Preston Guillot On

Does your array contain the internal names or the display names of the columns? If it's the latter you might try item[item.Fields[arrColName[i]].InternalName].ToStrinng(); instead.

0
Janis Veinbergs On

Not only check if item != null but also item["FieldName"] != null. Because if you will try to call .ToString() on null, you will get exception.

And if that field with internal name "FieldName" name does not exist, you will also get an exception. So you would probably try

SPFieldCollection fields = list.Fields;
foreach (SPListItem item in list.Items) {
  if (fields.Contains("FieldName") && item["FieldName"] != null) {
    string fieldValue = item["FieldName"].ToString();  
  }
}
1
Baris Bikmaz On

I think that you used an SPQuery to get the list items and forgot to add the field into the viewfields property of SPQuery.

query.ViewFields = string.Format("<FieldRef Name=\"{0}\" Nullable=\"True\" />", mFieldName);

Usually when you test your program with the farm account the code will work, with normal users you get an ArgumentException.

Another problem/feature which causes ArgumentException is the new ListView Threshold. If th elist you try to access has too many items, this Exception is raised. A way to handle this is to increase the threshold with powershell for the list.