user1133737
user1133737

Reputation: 113

Object reference not set to an instance of an object while reading file properties from SP2010

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();
}

Upvotes: 0

Views: 738

Answers (2)

Grant Winney
Grant Winney

Reputation: 66439

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.

Upvotes: 1

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

do like this:

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

 }
else
{
spDocumentType ="";

}

Upvotes: 1

Related Questions