Go Premium for a chance to win a PS4. Enter to Win

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

retrieving data from a database smallint column that may be null

Hi

I don't program in c# so i hope you might be able to help me on this.

I need to retrieve data from a databse which is contained in a datareader. One of the columns in the reader, call it index 0, is of type smallint and it might have a value of null. what type of variable do i need to store this? Perhaps its nullable of int but i don't know how to use one of these in c#. Also how do i check the column value is not null before i retrieve it from the reader using something like myvar = reader.getInt16(0)

thanks a lot
andrea
0
andieje
Asked:
andieje
  • 3
1 Solution
 
crisco96Commented:
Null from a database is different from the .Net null.

Null from a database will actual be System.Data.DBNull.

If you want to save the value from the reader to a variable do the following:
int? Value;
 
if(Reader[0] == System.Data.DBNull)
{
   Value = null;
}
else
{
   Value = Convert.ToInt32(Reader[0]);
}

Open in new window

0
 
andiejeAuthor Commented:
hi, i tried that and got this error

Invalid attempt to read from column ordinal '4'.  With CommandBehavior.SequentialAccess, you may only read from column ordinal '5' or greater.
  if (reader[4] != DBNull.Value)
                            {
                               
                                subcontractorID = Convert.ToInt16(reader[4]);
                            }
                            else
                            {
                                subcontractorID = null;
                            }
                         
0
 
andiejeAuthor Commented:
I CHANGED IT to this
   if (reader["subcontractorID"] != DBNull.Value)
                            {
                               
                                subcontractorID = Convert.ToInt16(reader[4]);
                            }
                            else
                            {
                                subcontractorID = null;
                            }
                         

thanks
0
 
andiejeAuthor Commented:
thanks
0
 
Hendo1973Commented:
You could use Nullable types which would allow value types to have a null value assigned to them.
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

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