It is not possible to implicitly convert the type 'object' to 'System.DateTime'. An explicit conversion exists (do you miss the role?)

I am developing my first program and am encountering some problems, please help me fill it out. I have this code in C #:

SqlDataReader dr = null;
dr = cmd.ExecuteReader();
if (dr.Read()) 
{
client_id = dr["clientid"].ToString();
surname = dr["surname"].ToString();
othername = dr["othername"].ToString();
gender = dr["gender"].ToString();
date_ofbirth = dr["dateofbirth"];
nationality = dr["nationality"].ToString();
//age = dr["Age"];
residential_address = dr["residentialaddress"].ToString();
postal_address = dr["postaladdress"].ToString();
contact_number = dr["telephonenumber"].ToString();
marital_status = dr["maritalstatus"].ToString();
spouse_name = dr["spousename"].ToString();
email = dr["email"].ToString();
occupation = dr["occupation"].ToString();
typeof_id = dr["typeofid"].ToString();
id_number = dr["idnumber"].ToString();
id_expirydate = dr["idexpirydate"];
remarks = dr["remarks"].ToString();
picture = dr["picture"].ToString();
return true;
cmd.CommandText = null;
}

and the error message for this is -............... date_ofbirth = dr ["dateofbirth"];

Error 2: It is not possible to implicitly convert the type 'object' to 'System.DateTime'. Explicit conversion exists

(do you miss the role?)

C: \ Users \ MICKY \ Documents \ Visual Studio 2008 \ Projects \ Godswill \ Godswill \ Personal.cs 249 28 Godswill

+5
source share
4 answers

You should give up all of these, and not blindly use ToString():

date_ofbirth = (DateTime) dr["dateofbirth"];

"unbox" .

, ORM -ORM (, "dapper" ) - :

var user = connection.Query<User>("select * from Users where Id=@id",
         new {id = 123}).First(); // (this is using "dapper")

User - , , ..

public class User {
    public string Surname {get;set;}
    ...
    public DateTime DateOfBirth {get;set;}
}

; , using , ..

using(SqlDataReader dr = cmd.ExecuteReader())
{
    if (dr.Read()) {...etc...}
}

.., Dispose() d, . "init null, set to null at the end" , - : p

+15

-

myVar = dr["myColumnName"];

dr["myColumnName"] . , :

myVar = (ExpectedType)dr["myColumnName"];
+2
date_ofbirth = DateTime.Parse(dr["dateofbirth"].ToString());

:

DateTime.TryParse(dr["dateofbirth"].ToString(), out date_ofbirth);
0
source

You will need to use Convert.ToDateTimeon dr["dateofbirth"], as well as on dr["idexpirydate"](since age will be int Convert.ToInt32for Age, if that doesn't work either!)

The type is returned object, and you will need to point it specifically to a specific DataType, but not all of them are strings, so ToString()there will be no choice for all of them.

It would also be nice to check DBNullif you are not using null data types

0
source

All Articles