Question

I have two textboxes : TextBox1 and TextBox2 both have date.

I want to get date difference in third textbox, that is TextBox3.

My code is:

protected void TextBox1_TextChanged(object sender, EventArgs e)
{
    TextBox3.Text = ((Convert.ToInt32(TextBox1.Text) - Convert.ToInt32(TextBox2.Text)).ToString());
}

protected void TextBox2_TextChanged(object sender, EventArgs e)
{
    TextBox3.Text = ((Convert.ToInt32(TextBox1.Text) - Convert.ToInt32(TextBox2.Text)).ToString());
}
Était-ce utile?

La solution 2

DateTime d1 = TextBox1.Text!=string.Empty?Convert.ToDateTime(TextBox1.Text): DateTime.MinValue;
DateTime d2 = TextBox2.Text!=string.Empty?Convert.ToDateTime(TextBox2.Text):DateTime.MinValue;
TimeSpan tspan= d2-d1;
TextBox3.Text = tspan.TotalDays.ToString();

Autres conseils

Convert both input values to DateTime, as in

DateTime dt1 = DateTime.Parse(TextBox1.Text);
DateTime dt2 = DateTime.Parse(TextBox2.Text);

Then, subtract both to get a TimeSpan object:

TimeSpan ts = dt1 - dt2;

Then you can use the properties of ts to set the value of the third text box:

TextBox3.Text = ts.TotalDays.ToString();

I assume here that valid dates are input into both text boxes, otherwise you'll get an exception in the first line above. You can alternatively look into the ParseExact or TryParse/TryParseExact methods provided by the DateTime class.

Try like this

DateTime d1 = Convert.ToDateTime(TextBox1.Text);
DateTime d2 = Convert.ToDateTime(TextBox2.Text);
TimeSpan span = d2-d1;
TextBox3.Text = span.TotalDays.ToString();
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top