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 DateTime
value itself. The dropdown displays its members by calling ToString()
. The disadvantage here: you are not able to use another time format like ToShortTimeString()
.
Another way is to use the DateTime.TryParse
method to convert back before calculating.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.