FrustratedProgrammer
FrustratedProgrammer

Reputation: 21

Adding a year to date in vb.net

I have two DateTimePicker controls on a form.

How can I automatically add a year to the date I have selected in the 1st DateTimePicker and display it on the 2nd DateTimePicker? For example, if select a date 09/22/2017, then I want the 2nd DateTimePicker to display 09/22/2018.

Is this possible? If so, would you suggest some appropriate code? If not, would you suggest an alternative way to do it?

enter image description here

Upvotes: 0

Views: 5282

Answers (3)

InteXX
InteXX

Reputation: 6367

You can do it like this, using the DateTimePicker's ValueChanged event:

Private Sub DateTimePicker1_ValueChanged(Sender As DateTimePicker, e As EventArgs) Handles DateTimePicker1.ValueChanged
  Me.DateTimePicker2.Value = Sender.Value.AddYears(1)
End Sub

To automatically generate this event handler code, double-click the first DateTimePicker control on your form.

You'll notice in this example that I've changed the casting of Sender from Object to DateTimePicker, so we can get IntelliSense in the IDE.

Upvotes: 1

Kiran Rai Chamling
Kiran Rai Chamling

Reputation: 498

If you are selecting a date then take the year from the datepicker. Append it to the textbox below.

You can do it in this way.

year = dtp1.Value.Year
tb.Text = tb.text + year

This will just append the year when you change the datepicker however if you want tb.Text year to be replaced on every click of datepicker then you should do something like this.

Dim str as String  = tb.Text        'Save current text
Dim arr as String() = str.Split(",")'Get previous text
currentYear = dtp1.Value.Year       'Get current year
tb.Text = arr(0) + currentYear      'Replace year in textbox with new year

Upvotes: 0

Prescott Chartier
Prescott Chartier

Reputation: 1653

Not sure what exactly you need to do and what YEAR you're looking for, but the simple answer is:

SomeComboBox.text = Now.Year

Upvotes: 0

Related Questions