• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 544
  • Last Modified:

Working with DBNulls

When you use a SQLDataReader, there is a method, GetSqlInt32, where you get a value from the data reader and it returns a SqlInt32object. If the field you get is Null, it simply initializes the SQLInt32 Object to hold the value 0. BUT. If you try to make a NEW SqlInt32 based on the same field but from a DataRow instead, it returns an error. Anybody know a way around this?
0
drokliss
Asked:
drokliss
  • 6
  • 2
1 Solution
 
naveenkohliCommented:
.Net framework is strongly typed environment. IF you will try to create an object with wrong type of arguments it will throw an exception at you. What you will need to do is check if the value in DataField is DBNull or not. If its DBNull, then don't try to set it in SqlInt32.
0
 
droklissAuthor Commented:
Then why would the Datareader initialize a null value when you call the GetSqlInt32 method?
0
 
droklissAuthor Commented:
Then why would the Datareader initialize a null value when you call the GetSqlInt32 method?
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
droklissAuthor Commented:
Then why would the Datareader initialize a null value when you call the GetSqlInt32 method?
0
 
droklissAuthor Commented:
ack! Stinking refresh. Sorry about triple posting
0
 
naveenkohliCommented:
Since SqlInt32 is a structure so its is a value type. And the default value for this unsigned interger type is 0. You can experiment yourself. Just defaine a SqlInt32 variable and don't assign any value to it. By default it will pick up {0}.
Now try to assign "null" to this variable. It will not compile.

Therefore if you will try to assign a DBNull value to it from DataRow it will throw run timne exception at you.

GetSqlInt32 is not supposed to do any conversions. Check if you NULL value for that field in column in database.
This could very well be bug in the call.

To make sure, call GetValue on DataReader for that field. And check if that "object" is of type DBNull or not.

Naveen

0
 
droklissAuthor Commented:
I know for a fact that the value in the database is null. For whatever reason, the GetSqlInt32 method on the datareader was set up to initialize to its default value when the column passed into it is null. Thanks for your help anyway.
0
 
droklissAuthor Commented:
Helpful knowledge.
0

Featured Post

Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

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