When you somehow work with data in SharePoint list the important thing is that you should beware of empty fields.
This code seems to be ok and it would perfectly work until one of the "Name" fields wouldn't be empty:
foreach (SPListItem row in list.Items)
{
Console.WriteLine("Value of field is: {0}", row["Number"].ToString());
}
Problem is that SharePoint doesn't save empty field as empty string if you would create a new item and left "Number" field empty. So if there is no condition you would get this error: Object reference not set to an instance of an object. because of the field which user didn't fill, the new instance of object wasn't created. (at least, it's what I think, but anybody who knows real reason can comment it ;) )
For me was the best practice to check every field which user isn't enforced to fill and could be empty.
You can use this code to check values:
foreach (SPListItem row in list.Items)
{
//Checks if "Number" field contain any data
if (row["Number"] != null)
Console.WriteLine("Value of field is: {0}", row[myLookupColumnName].ToString());
}
or another way how to treat empty field is to use try and catch block like this:
foreach (SPListItem row in list.Items)
{
//Tries to catch exception
try
{
Console.WriteLine("Value of field is: {0}", row[myLookupColumnName].ToString());
}
catch (NullReferenceException ex)
{
Console.WriteLine("The field was empty. Error: " + ex.Message);
}
}
If somebody use another way how to check data in field I would be glad to hear it :)
Happy coding
David
No comments:
Post a Comment