C# - SQL - Null int problems

  • Thread starter Thread starter Dan
  • Start date Start date
D

Dan

I'm fairly new to C# and I am having some problems
understanding int variables and null values.

I have created a class that populates the values of it's
fields from a DataReader in it's constructor. Those fields
are modified during various methods in the class. One
method updates the database with the values of the class
fields. I have everything working fine for string fields
but am running into problems with integers and null values.

The problem is that if I try to set a null int field from
the database to an int field in the class I get an
error.... so I've had to add the following check...
=================================================
if (dr["myID"] != System.DBNull.Value){
_myID = Convert.ToInt32(dr["myID"]);
}
=================================================
..... so now if the db value was null, then the class field
never gets initialized.


When I declare the variable I am not able to set the value
as null, or I get the error "Cannot convert null to int
because it is a value type".
==================================================
private int _myID = null;
==================================================


In the update method I want to be able to update the
database to whatever the value of the class field is (null
or otherwise).
==================================================
cmd.Parameters.Add("@myID", System.Data.SqlDbType.Int,
4).Value = _myID;
==================================================
.....but the problem is that if the field never got
initialized, then this crashes. I want to be able to test
the value if it is null, but I can't set it to null.


-- How do I deal with this?
-- Is there a way to check to see if this int field has
been initialized?
-- Is there a better way to set an int field to a null
value?


Any help is greatly appreciated.

-Dan
 
The problem is that if I try to set a null int field from
the database to an int field in the class I get an
error.... so I've had to add the following check...
=================================================
if (dr["myID"] != System.DBNull.Value){
_myID = Convert.ToInt32(dr["myID"]);
}

You might also use IsDBNull method.
=================================================
.... so now if the db value was null, then the class field
never gets initialized.


-- How do I deal with this?

I've created a class for each type.
It has methods such as IsNull, etc.
-- Is there a way to check to see if this int field has
been initialized?

You might consider using int.MinValue as a null value.
Though I prefer the above approach.
There are also Sql* types, such as SqlInt32. However they are not very
usable for this purpose.
-- Is there a better way to set an int field to a null
value?

Nope.
 
Back
Top