M A Hossan M A Hossan - 1 year ago 89
ASP.NET (C#) Question

Invalid cast from 'Int32' to 'DateTtime

I am trying to achieve if database current records(data and month) is less than 6 month then if statement will be executed and display the message in Label control is "Please come back after 6 months". The present date and time should be catch from DateTime. otherwise if the current of database grater than 6 month then else if statement will executed and display the message in Label control is "You can apply" . If the both if or if else is not true then I want to say "You can not apply

SqlCommand cmd = new SqlCommand("SELECT Date FROM Decline_Credit_Card_Application WHERE Account_Number = @Account_Number", cn);
cmd.Parameters.AddWithValue("Account_Number", TextBox1.Text);
object value = cmd.ExecuteScalar();
// DateTime dt = Convert.ToDateTime(value);
//DateTime inSixMonths = DateTime.Now.AddMonths(6);

if (Convert.ToDateTime(value) <DateTime.Now.AddMonths(-month))

Label1.Text = "Elligible ";

else if (Convert.ToDateTime(value) > DateTime.Now.AddMonths(-month))

Label1.Text = "Not Elligible ";

Label1.Text = "No record found";


Answer Source

You can't create a DateTime out of a integer value.

int month = 6;
Convert.ToDateTime(month); //Invalid cast from 'Int32' to 'DateTime'

To get your desired output replace

if(Convert.ToDateTime(value) > Convert.ToDateTime(month))


if(Convert.ToDateTime(value) < DateTime.Now.AddMonths(-month))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download