0

I am trying to use code to use a CAML query to pull data from a list...when I iterate through the data returned by my query and try to assign them to variables in my code, I get some nullException when the fields in the list have no data (null). What would be the recommended way to get my variables to return just an empty string, if there is blank data returned for any field in from my list. Here is what my snippet looks like...so right now when there is no data from the list, my field variables are throwing a null exception. How can I get them to hold a whitespace (blank)? Or get past this exception?

SPList myList = currentWeb.Lists["MyListName"];
SPQuery query = new SPQuery();

query.Query = @"";

SPListItemCollection myCollection = mydList.GetItems(query);

foreach (SPListItem item in myCollection)
{
    string field1 = item["fieldone"].ToString();
    string field2 = item["fieldtwo"].ToString();
    string field3 = item["fieldthree"].ToString();
    string field4 = item["fieldfour"].ToString();

}
Spawn10
  • 13
  • 2
  • `if (myCollection != null) ...` ? – Ňɏssa Pøngjǣrdenlarp Jul 14 '16 at 21:30
  • @Plutonix The collection can never be null. – Servy Jul 14 '16 at 21:31
  • If it's because the collection doesn't have the field, and also if `SPListItemCollection` has the `Contains()` method then you can do, `if (item.Contains("fieldone")) { string field1 = item["fieldone"].ToString(); }`. If it's because the item itself is `null` then you can do `if (item["fieldone"] != null) { string field1 = item["fieldone"].ToString(); }`. Or just fall back to `try/catch` (not recommended, avoiding exceptions should always be step 1, only try/catch unavoidable exceptions). – Quantic Jul 14 '16 at 21:35
  • Maybe you could loop each item and check is it null or empty for example if(String.IsNullOrEmpty(yourItem))){set your field to empty quotation marks as you asked in your question .. so it might look something like this `if(String.IsNullOrEmpty(yourlistitem){string field1="";}` and so on} –  Jul 14 '16 at 21:41

0 Answers0