Calculate difference between two dates from DateTimePicker using C# in Windows Forms Application

Last Reply one year ago By dharmendr

Posted one year ago

hi all, i have two textbox that contains datepickers, what i want is a code that can generate the two dates that i have picked from the datepickers and display the total days inside the third textbox


Posted one year ago Modified on one year ago

Hi lingtyson,

Check this example. Now please take its reference and correct your code.



private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
    DateTime inTime = Convert.ToDateTime(dateTimePicker1.Text);
    DateTime outTime = Convert.ToDateTime(dateTimePicker2.Text);
    if (outTime >= inTime)
        textBox1.Text = outTime.Subtract(inTime).Days.ToString();


Private Sub dateTimePicker1_ValueChanged(ByVal sender As Object, ByVal e As EventArgs)
    Dim inTime As DateTime = Convert.ToDateTime(dateTimePicker1.Text)
    Dim outTime As DateTime = Convert.ToDateTime(dateTimePicker2.Text)
    If outTime >= inTime Then
        textBox1.Text = outTime.Subtract(inTime).Days.ToString()
    End If
End Sub


Posted one year ago

Already provided you the complete code. Please check does you have assigned event handler for both the DateTimePicker.

If you have not assigned the go to the property of DateTimePicker and assign ValueChanged event handler for these.

You can also assign using code behind. For this you need to add the below line of code.

public Form1()
    dateTimePicker1.ValueChanged += new EventHandler(dateTimePicker1_ValueChanged);
    dateTimePicker2.ValueChanged += new EventHandler(dateTimePicker1_ValueChanged);