Reputation: 113
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
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
Reputation: 62488
do like this:
if(spFile.Properties["DocumentType"] !=null)
{
spDocumentType = spFile.Properties["DocumentType"].ToString() == "INV" ? spFile.Properties["DocumentType"].ToString() : "";
}
else
{
spDocumentType ="";
}
Upvotes: 1