views:

1225

answers:

8

Hi All,

I have got a 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
}

Please advice. Thanks

A: 

Try this:

string tempValue =  item[arrColName[i]] as string;
Rubens Farias
A: 

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]

Zigu
A: 

Thanks for the replies.Tried Rubens but did not help. Zigu, You are right and i am actually getting the SPListItems iterating through the SPListItemsCollection but the issue is in getting the item values through indexer which throws argumentexception if the column value is null.

ProdShare
A: 

item[colname] throws argumentexception- values does not fall in expected range

ProdShare
+1  A: 

Check it for null first.

if(item!=null)
{
  // work on item
}
Nick Haslam
A: 

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.

OedipusPrime
A: 

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();  
  }
}
Janis Veinbergs
A: 

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 dont work).

Jamil