c# - Cannot implicitly convert type 'object' to 'System.DateTime'. An explicit conversion exists (are you missing a cast?) -


i developing first programm , facing problems please me complete have 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 error message ............... date_ofbirth = dr["dateofbirth"];

error 2 cannot implicitly convert type 'object' 'system.datetime'. explicit conversion exists

(are missing cast?)

c:\users\micky\documents\visual studio 2008\projects\godswill\godswill\personal.cs 249 28 godswill

you should cast all of those, rather blindly using tostring():

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

this "unbox" value needed.

of course, easier approach here use orm or micro-orm (such "dapper") - run:

var user = connection.query<user>("select * users id=@id",          new {id = 123}).first(); // (this using "dapper") 

where user class properties match table definition, i.e.

public class user {     public string surname {get;set;}     ...     public datetime dateofbirth {get;set;} } 

also; make sure read using here, i.e.

using(sqldatareader dr = cmd.executereader()) {     if (dr.read()) {...etc...} } 

this more important connections etc, acts ensure resource correctly dispose()d if there error. replaces "init null, set null @ end" code, , has advantage of doing ;p


Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -