I have a problem with the dates. I cant get the .AddYears() method to work. Can somebody please have a look on what I am doing wrong here.
MySqlConnection myMySqlConnection = new MySqlConnection(connectionString);
MySqlDataAdapter da = new MySqlDataAdapter();
MySqlCommand cmd1;
cmd1 = new MySqlCommand("SELECT INITIAL_DATE FROM USERS WHERE ID = @id1", myMySqlConnection);
cmd1.Parameters.AddWithValue("@id1", id);
myMySqlConnection.Open();
da.SelectCommand = cmd1;
DateTime initial_date = (DateTime)cmd1.ExecuteScalar();
myMySqlConnection.Close();
From this point and below is the problem:
DateTime[] dates = new DateTime[20];
dates[0] = Convert.ToDateTime(initial_date);
for (int i = 1; i < 20; i++)
{
dates[i] = initial_date.AddYears(1);
}
initial_date.AddYears(1);was repeatedly adding 1 to the same value so all DateTimes after the initial one were of the same value. DateTime is immutable, so calls to its methods do not change its value, but return a new instance with the desired value. You need to change it toinitial_date.AddYears(i);Change your problem code to:
It will give you the results you need.