Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 193
  • Last Modified:

How to tell if this field is null

In the following statement, there is sometimes nothing in that field, which causes an exception.

How do I tell in if the field is valid so as to not cause the exception?

while (dr.Read()) {
    decimal workingPrice = dr.GetDecimal(5);
}

Open in new window

0
rmmarsh
Asked:
rmmarsh
  • 3
  • 3
1 Solution
 
anarki_jimbelCommented:
Call IsDBNull to check for null values before calling this method.

See:

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getdecimal.aspx
0
 
anarki_jimbelCommented:
Just in case, if not clear:

if(!dr.isDBNull){
  decimal workingPrice = dr.GetDecimal(5);
}


I can also make a suggestion to use nullable types. But it depends on what you need. Have a look:

http://www.c-sharpcorner.com/UploadFile/mosessaur/nullabletypes08222006164135PM/nullabletypes.aspx

But in any case before using GetDecimal you need to check for DBNull.
0
 
rmmarshAuthor Commented:
Your syntax is wrong for IsDBNull... it only works on 'int', not decimal.  Thanks anyway!
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
rmmarshAuthor Commented:
Correct syntax is:                      if (!dr.IsDBNull(5))

Thanks anyway...
0
 
rmmarshAuthor Commented:
Answer was 'close', but not correct.  He gave me something to work with, tho'
0
 
anarki_jimbelCommented:
Of course, experts also do mistakes. Especially if are not using VS at the moment :)

By the way, excellent practice to give RIGHT solutions as you did. For those who will search for solutions in future. Thanks.
0

Featured Post

[Webinar On Demand] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now