I have to 2 dropdownlists and I want to populate them with their values as hours from 1 to 24. Then I want to calculate the difference between the two selected values. If i choose in the first dropdown let’s say the hour value as 12 AND second value as 16 then the difference will be 4.
How can I achieve that in c#?
I’m developing a asp.net web application coded in C#.
Below is the code of how I populate my dropdownlist:
DateTime Date = DateTime.Today;
DateTime Time = DateTime.Now;
ListItem item1 = new ListItem(Time.ToShortTimeString(),
Time.ToShortTimeString());
for (int i = 0; i <= 48; i++)
{
ListItem item2 = new ListItem(Date.ToShortTimeString(),
Date.ToShortTimeString());
droplist.Items.Add(item2);
if (Date.CompareTo(Time) < 0 && Date.AddMinutes(30).CompareTo(Time) > 0)
droplist.Items.Add(item1);
Date = Date.AddMinutes(60);
}
How can I assign values to my dropdown, values being the hours?
Instead of adding the date/time string to the drop down, you may add the
DateTimevalue itself. The dropdown displays its members by callingToString(). The disadvantage here: you are not able to use another time format likeToShortTimeString().Another way is to use the
DateTime.TryParsemethod to convert back before calculating.