Quantcast
Viewing all articles
Browse latest Browse all 12583

How to get 2 datetimepicker controllers's difference in year, month and days in C#? Why my messagebox is appearing mone than once?

Dear all,

I have designed a form with two datetimepicker so that changing anyone, the labels should show the difference in year, month and days. I have made it manually but in some cases it is giving some error. Can anyone solve my problem with built-in function directly?

Secondly, I have prepared a message box for avoiding negative result. It is coming but it is appearing 2/3 times consecutively and then minimizing the main program! Can anyone solve it for me?

Thanks everyone.

My coding is as follows:

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            if (dateTimePicker2.Value > dateTimePicker1.Value)
            {
                TimeSpan age;
                age = dateTimePicker2.Value - dateTimePicker1.Value;
                int year;
                int month;
                int day;
                year = age.Days / 365;
                month = (age.Days % 365) / 30;
                day = (age.Days % 365) % 30;
                label7.Text = year.ToString();
                label8.Text = month.ToString();
                label9.Text = day.ToString();
            }
            else
            {
                label7.Text = label8.Text = label9.Text = "0";
                dateTimePicker1.Value = dateTimePicker2.Value = System.DateTime.Now;
                MessageBox.Show("From date must be earlier than To date!",
                    "Error!",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Exclamation,
                    MessageBoxDefaultButton.Button1);
            }
        }


Viewing all articles
Browse latest Browse all 12583

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>