On the one hand, I have an Access database, where Tbl_Application.id_connexion is a field of type Guid (called the "replication identifier" in ms Access terminology).
I am collecting some data from this Tbl_Application table through the DataRow[] array, dr_Tbl_Application . The following code reads the first DataRow:
private Guid? mid_connexion = null; mid_connexion = (Guid)dr_Tbl_Application[0]["id_connexion"]
Everything is fine as long as Tbl_Application.id_connexion contains the value. If this field does not contain a value, I will get the following error:
InvalidCastException was unhandled
And these are some of the things that I see in the next window:
? dr_Programme[0]["id_Connexion"] {} ? dr_Programme[0]["id_Connexion"].GetType() {Name = "DBNull" FullName = "System.DBNull"} ? dr_Programme[0]["id_Connexion"] is System.DBNull true
So, to avoid my exception, I think it's best to check before passing the unique identifier value from a field in the database to a local variable. That said, my discovery is still bothering me, and I would like to delve deeper into this problem.
My questions are as follows:
- Is there a way to write some basic code to assign a value from a database. Guid value for local Guid object without checking on
System.DBNull ? - Why does the same instruction applied to the same object return different types, depending on whether the source fields are or not?
Change to question 2:
? dr_Programme[0]["id_Connexion"].GetType()
returns the type System.Guid when the corresponding field is populated in the source table, and
? dr_Programme[0]["id_Connexion"].GetType()
returns the type System.DBNull when the field is null (or empty) in the source table ...