0

I have sharepoint document library which has custom field called "DocumentType" this is not mandatory field. When I am trying to read this property using the below code, when value is there in this field its working fine but where its value empty giving the error "Object reference not set to an instance of an object." If value is not there I need to pass empty string for further logic, how can I handle this?

SPFile spFile=Web.GetFile(Context.Request.Url.ToString());
string spDocumentType=string.Empty;
if (spFile.Properties["DocumentType"].ToString() == "INV") *In this line exception throwing where value is empty in this field in the doc library.
{
spDocumentType = spFile.Properties["DocumentType"].ToString();
}
John Saunders
  • 160,644
  • 26
  • 247
  • 397
user1133737
  • 113
  • 5
  • 22

2 Answers2

1

do like this:

if(spFile.Properties["DocumentType"] !=null)
 {
   spDocumentType = spFile.Properties["DocumentType"].ToString() == "INV" ? spFile.Properties["DocumentType"].ToString() : "";

 }
else
{
spDocumentType ="";

}
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
1

Change this piece of code:

spFile.Properties["DocumentType"].ToString()

To this:

Convert.ToString(spFile.Properties["DocumentType"])

While ToString() throws the exception you're getting when the value is null, the Convert.ToString() method tests for null and returns an empty string.

Grant Winney
  • 65,241
  • 13
  • 115
  • 165