I am developing my first programm and am facing some problems please help me complete it 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 Cannot implicitly convert type 'object' to 'System.DateTime'. An explicit conversion exists
(are you missing a cast?)
C:\Users\MICKY\Documents\Visual Studio 2008\Projects\Godswill\Godswill\Personal.cs 249 28 Godswill
You should cast all of those, rather than blindly using ToString():
date_ofbirth = (DateTime) dr["dateofbirth"];
This will "unbox" the value as needed.
Of course, an easier approach here is to use an ORM or micro-ORM (such as "dapper") - then you just run:
var user = connection.Query<User>("select * from Users where Id=@id",
new {id = 123}).First(); // (this is using "dapper")
where User is a class with properties that match the table definition, i.e.
public class User {
public string Surname {get;set;}
...
public DateTime DateOfBirth {get;set;}
}
Also; make sure you read about using here, i.e.
using(SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.Read()) {...etc...}
}
this is even more important for connections etc, but it acts to ensure the resource is correctly Dispose()d even if there is an error. This replaces your "init as null, set to null at the end" code, and has the advantage of actually doing something ;p
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With