I'm currently doing my current project and I had a problem. Here's what the project needs to do:
Find the maximum and the minimum temperature from a certain range of date. The range of the date will be inputted by the user.
So, I make a form as the main menu for inputting the items and finding the maximum and minimum value (both in the new form). I also make a class to store the items:
public class TempDate
{
public double Temp { get; set; }
public DateTime Date { get; set; }
}
In the first form, just call it FormAddData, from here items will be stored into the list using a textbox and here's the code:
private void buttonSubmit_Click(object sender, EventArgs e)
{
FormMenu formMenu = (FormMenu)this.Owner;
DateTime date = dateTimePickerDate.Value.Date;
double temp = double.Parse(textBoxTemp.Text);
TempDate tempDate = new TempDate();
tempDate.Date = date;
tempDate.Temp = temp;
formMenu.listOfTempDate.Add(tempDate);
listBoxInfo.Items.Add(date + "\t" + temp + "°C");
}
In the second form that called FormMaxMinRange. In this form, I use two DateTimePicker the first one for the starting date and the second for the ending date. From here I need to make a button that will select all the items from the range that I used from starting and ending date. Here's my code:
private void buttonMaxMin_Click(object sender, EventArgs e)
{
FormMenu formMenu = (FormMenu)this.Owner;
DateTime start = dateTimePickerStart.Value.Date;
DateTime end = dateTimePickerEnd.Value.Date;
int highest = 0;
double max = formMenu.listOfTempDate[0].Temp;
int lowest = 0;
double min = formMenu.listOfTempDate[0].Temp;
for (int i = 1; i < formMenu.listOfTempDate.Count; i++)
{
if (formMenu.listOfTempDate[i].Date >= start
&& formMenu.listOfTempDate[i].Date <= end)
{
if (formMenu.listOfTempDate[i].Temp > max)
{
highest = i;
max = formMenu.listOfTempDate[i].Temp;
}
if (formMenu.listOfTempDate[i].Temp < min)
{
lowest = i;
min = formMenu.listOfTempDate[i].Temp;
}
}
}
listBoxMaxMin.Items.Add("");
listBoxMaxMin.Items.Add("Lowest temp: " + min + ", on " + formMenu.listOfTempDate[lowest].Date);
listBoxMaxMin.Items.Add("Highest temp: " + max + ", on " + formMenu.listOfTempDate[highest].Date);
}
Here's the main form that i declared the class (which include the list):
public partial class FormMenu : Form
{
public List<TempDate> listOfTempDate = new List<TempDate>();
public FormMenu()
{
InitializeComponent();
}
private void fromCertainRangeToolStripMenuItem_Click(object sender, EventArgs e)
{
FormMaxMinRange formMaxMinRange = new FormMaxMinRange();
formMaxMinRange.Owner = this;
formMaxMinRange.ShowDialog();
}
}
But, the problem is, the minimum value was not selected inside the range of selection. Also I want the max and min value was printed in the listbox. Sorry for the long and weird question. I hope someone can understand what I means with this question to complete my project. Thank you.
See this code snippet.
You can use Linq to select the reduced list (with Start/Enddate) and order it by Temp. Now you can easy select the first (min) and the last (max) object.
List<TempDate> loTempDateList = new List<TempDate>()
{
new TempDate() {Date = DateTime.Now.AddDays(-10), Temp = 10.01 },
new TempDate() {Date = DateTime.Now.AddDays(-5), Temp = 20.01 },
new TempDate() {Date = DateTime.Now.AddDays(-3), Temp = 30.01 },
new TempDate() {Date = DateTime.Now, Temp = 40.01 }
};
DateTime ldStart = DateTime.Now.AddDays(-6);
DateTime ldEnd = DateTime.Now.AddDays(-1);
var loDateList = loTempDateList.Where(item => item.Date <= ldEnd && item.Date >= ldStart)
.OrderBy(item => item.Temp);
TempDate loMin = loDateList.First();
TempDate loMax = loDateList.Last();
Console.WriteLine("{0}: {1} with max temp", loMax.Date, loMax.Temp);
Console.WriteLine("{0}: {1} with min temp", loMin.Date, loMin.Temp);
Output (for today):
9/26/2017 3:17:09 PM: 30.01 with max temp
9/24/2017 3:17:09 PM: 20.01 with min temp
Update (with your variable names):
Copy this under DateTime end = dateTimePickerEnd.Value.Date;in your Form
var loDateList = listOfTempDate.Where(item => item.Date <= end && item.Date >= start)
.OrderBy(item => item.Temp);
TempDate loMin = loDateList.FirstOrDefault();
TempDate loMax = loDateList.LastOrDefault();
if (loMin != null && loMax != null)
{
listBoxMaxMin.Items.Add("");
listBoxMaxMin.Items.Add("Lowest temp: " + loMin.Temp + ", on " + loMin.Date);
listBoxMaxMin.Items.Add("Highest temp: " + loMax.Temp + ", on " + loMax.Date);
}
I would suggest you use Linq Max and Min methods.
// filter out only the dates in the range you need
var items = formMenu.listOfTempDateWhere(
item => ((TempDate)item).Date >= start && ((TempDate)item).Date <= end
);
// get the maximum value
var max = items.Max(item => item.Temp);
// get the minimum value
var min = items.Min(item => item.Temp);
Just remember to add using System.Linq on the top of your .cs file
try this online
If you don't like a LINQ approach (I never use LINQ, for some, possibly invalid reason, I think it's evil), you can override the List class and extend it with methods of your own.
public class TempDataList<T> : List<TempData>
{
public TempDataList() : base()
{
}
public TempDataList(IEnumerable<TempData> collection) : base(collection)
{
}
public TempData GetMaxTemp(DateTime startDate, DateTime endDate)
{
TempData highestTempData = null;
for (int i = 0; i < this.Count; i++)
{
if (this[i].Date >= startDate && this[i].Date <= endDate)
{
if (highestTempData == null || this[i].Temp > highestTempData.Temp)
{
highestTempData = this[i];
}
}
}
return highestTempData;
}
public TempData GetMinTemp(DateTime startDate, DateTime endDate)
{
TempData lowestTempData = null;
for (int i = 0; i < this.Count; i++)
{
if (this[i].Date >= startDate && this[i].Date <= endDate)
{
if (lowestTempData == null || this[i].Temp < lowestTempData.Temp)
{
lowestTempData = this[i];
}
}
}
return lowestTempData;
}
}
And fill the extended list and call the methods:
TempDataList<TempData> tempDataList = new TempDataList<TempData>();
tempDataList.Add(new TempData(10, DateTime.UtcNow));
tempDataList.Add(new TempData(20, DateTime.UtcNow));
tempDataList.Add(new TempData(15, DateTime.MinValue));
tempDataList.Add(new TempData(25, DateTime.MaxValue));
Console.WriteLine(tempDataList.GetMaxTemp(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1)).Temp);
Console.WriteLine(tempDataList.GetMinTemp(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1)).Temp);
Related
I am trying to determine whether times ranges are overlapping on a CRUD page but am stuck.
I can get it working with two time ranges using the code below but I need it working for 3 as well.
public static bool IsOverLapping(ConfigureViewModel viewModel)
{
bool status = false;
var times = viewModel.Periods.OrderBy(x => x.StartTime.TimeOfDay).ToList();
for (var i = 0; i <= times.Count - 2; i++)
{
if (times[i].StartTime.TimeOfDay <= times[i + 1].EndTime.TimeOfDay)
{
if (times[i + 1].StartTime.TimeOfDay >= times[i].EndTime.TimeOfDay)
status = false;
else
return true;
}
else
return true;
}
return status;
}
The data comes in as DateTime values which is why I have only looked at the 'TimeOfDay' value. The image shows the layout of the CRUD page.
This is actually trickier than it seems, as you need to handle time periods that wrap across midnight.
Using some extension methods, you can make it straight forward.
First, determine if a time is between two others:
public static bool Between(this TimeSpan aTime, TimeSpan startTime, TimeSpan endTime) => (startTime <= endTime) ? (startTime < aTime && aTime < endTime)
: (startTime < aTime || aTime < endTime);
Then create a special version using the Period class for the range:
public static bool Between(this TimeSpan aTime, Period aPeriod) => aTime.Between(aPeriod.StartTime.TimeOfDay, aPeriod.EndTime.TimeOfDay);
Finally create a test for if one range overlaps a second range (note this is asymmetric):
public static bool Overlaps(this Period aPeriod, Period bPeriod) => aPeriod.StartTime.TimeOfDay.Between(bPeriod) || aPeriod.EndTime.TimeOfDay.Between(bPeriod);
Now go through all the ranges and check if any range overlaps another range:
public static bool IsOverLapping(this List<Period> periods) {
var periodCount = periods.Count;
for (int j1 = 0; j1 < periodCount; ++j1)
for (int j2 = 0; j2 < periodCount; ++j2)
if (j1 != j2 && periods[j1].Overlaps(periods[j2]))
return true;
return false;
}
Finally you can use the method in your ConfigureViewModel method:
public static bool IsOverLapping(ConfigureViewModel viewModel)
{
bool status = false;
var times = viewModel.Periods.OrderBy(x => x.StartTime.TimeOfDay).ToList();
return times.IsOverLapping();
}
I think it might be simpler than it sounds. If you have period1 and period2, they are NOT overlapping if period1.Start > period2.End or if period1.End < period2.Start. If neither of these are true, then we know that they are overlapping:
I made this a static method on the Period class:
public class Period
{
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public static bool AreOverlapping(Period first, Period second)
{
if (first == null || second == null) return false;
// These two conditions define "overlapping" and must be true
return first.StartTime <= second.EndTime &&
first.EndTime >= second.StartTime;
}
}
Then this should simplify the logic in your method that detects if there are any overlapping periods in a group:
public static bool DoAnyOverlap(List<Period> periods)
{
if (periods == null || periods.Count < 2) return false;
var ordered = periods.OrderBy(p => p.StartTime).ToList();
for (var i = 0; i < ordered.Count - 1; i++)
{
if (Period.AreOverlapping(ordered[i], ordered[i + 1])) return true;
}
return false;
}
If for some reason you cannot modify the Period class, the logic can easily be incorporated into the DoAnyOverlap method:
public static bool DoAnyOverlap(List<Period> periods)
{
if (periods == null || periods.Count < 2) return false;
var ordered = periods.Where(p => p != null).OrderBy(p => p.StartTime).ToList();
for (var i = 0; i < ordered.Count - 1; i++)
{
if (ordered[i].StartTime <= ordered[i + 1].EndTime &&
ordered[i].EndTime >= ordered[i + 1].StartTime)
{
return true;
}
}
return false;
}
Try this:
var periods = new[]
{
new { start = TimeSpan.Parse("10:00"), end = TimeSpan.Parse("14:00") },
new { start = TimeSpan.Parse("16:00"), end = TimeSpan.Parse("17:00") },
new { start = TimeSpan.Parse("13:00"), end = TimeSpan.Parse("15:00") },
};
bool overlapping =
Enumerable
.Range(0, periods.Length)
.SelectMany(i =>
Enumerable
.Range(i + 1, periods.Length - i - 1),
(i, j) => new { A = periods[i], B = periods[j] })
.Any(x => !(x.B.start >= x.A.end || x.B.end <= x.A.start));
It'll work with DateTime too.
Assuming ConfigureViewModel class looks like that:
class ConfigureViewModel
{
...
public List<Period> Periods { get; set; }
}
class Period
{
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
}
You can use Time Period Library for .NET:
PM> Install-Package TimePeriodLibrary.NET
And IsOverLapping mathod may look as simple as that:
public static bool IsOverLapping(ConfigureViewModel vm, int numberOfOverlaps)
{
var ranges = vm.Periods.Select(q => new TimeRange(q.StartTime, q.EndTime));
TimePeriodCollection periodCollection = new TimePeriodCollection(ranges);
TimePeriodIntersector<TimeRange> intersector = new TimePeriodIntersector<TimeRange>();
return intersector.IntersectPeriods(periodCollection).Count > numberOfOverlaps;
}
can someone help me with my payroll system codes. I want a result where i will get the total number of hours of each employee and before proceeding to another employee it will be saved in a table in mysql. the problems im encountering are
1. it still counts the datetime even if it is null in database.
2. after changing the timeline it still counts the previous total hours
the variable does not reset.
enter image description here
public int IdFrom;
public int Idto;
public int TotalHours;
public int day;
public DateTime time1;
public DateTime time2;
public string testNull;
public string date;
public string testvariable;
string testdate1;
string testdate2;
TimeSpan totaltime;
TimeSpan ts;
private void btn_compute_Click(object sender, EventArgs e)
{
if (rb_all.Checked == true)
{
cls.Connection();
cls.connect.Open();
cls.command = new MySqlCommand("select ID from tbl_attendance order by ID asc limit 1", cls.connect);
cls.reader = cls.command.ExecuteReader();
while (cls.reader.Read())
{
IdFrom = cls.reader.GetInt16(0);
}
cls.reader.Close();
cls.Connection();
cls.connect.Open();
cls.command = new MySqlCommand("select ID from tbl_attendance order by ID desc limit 1", cls.connect);
cls.reader = cls.command.ExecuteReader();
while (cls.reader.Read())
{
Idto = cls.reader.GetInt16(0);
}
cls.reader.Close();
for(int x = IdFrom;x<=Idto;x++)
{
totaltime = TimeSpan.Zero;
ts = TimeSpan.Zero;
day = 0;
TotalHours = 0;
testNull = "";
date = "";
DateTime dt = DateTime.Parse(start_date.Text);
DateTime dt2 = DateTime.Parse(end_date.Text);
ts = dt2 - dt;
day = ts.Days;
for (int y = 0; y <= day; y++)
{
date = dt.AddDays(y).ToString("yyyy")
+ "-" + dt.AddDays(y).ToString("MM")
+ "-" + dt.AddDays(y).ToString("dd");
cls.Connection();
cls.connect.Open();
cls.command = new MySqlCommand("select Time_In,Time_Out from tbl_attendance where Date = '" + date + "' and ID = "+x+"", cls.connect);
cls.reader = cls.command.ExecuteReader();
while (cls.reader.Read())
{
time1 = DateTime.Parse(cls.reader.GetValue(0).ToString());
time2 = DateTime.Parse(cls.reader.GetValue(1).ToString());
}
cls.reader.Close();
MessageBox.Show(time1.ToString());
MessageBox.Show(time2.ToString());
totaltime = time2 - time1;
MessageBox.Show(totaltime.Hours.ToString());
if (totaltime.Hours == 0)
{
}
else
{
TotalHours = TotalHours + (int.Parse(totaltime.Hours.ToString()) - 1);
}
}//total hours computed
if (totaltime.Hours == 0)
{
break;
}
else
{
MessageBox.Show(TotalHours.ToString());
break;
}
}//end of for loop for total number of hours
}
I am creating a WPF application using MVVM. I am wanting to create a basic list of bookings for a certain date that are pulled back from a database, but also include blank spaces in the list (to be displayed in a listbox) to show when there is free time in between bookings, during working hours.
So far I can get blank spaces adding but only for the empty gaps within 2 bookings, whereas I want the spaces to be displayed for every hour from 9:00 until 21:00.
private void CheckForGaps(List<DisplayBookingDetails> list)
{
DateTime endIndex;
DateTime startIndex;
int minBookingLength = 60;
DisplayBookingDetails[] test;
DisplayBookingDetails nullMarker = null;
DateTime dayStart = new DateTime(0001, 01, 01).AddHours(09).AddMinutes(00).AddSeconds(00);
DateTime dayEnd = new DateTime(0001, 01, 01).AddHours(21).AddMinutes(00).AddSeconds(00);
test = list.ToArray();
List<DisplayBookingDetails> testList = new List<DisplayBookingDetails>();
for (int i = 0; i < test.Length; i++)
{
if (i > 0)
{
endIndex = list[i - 1].EndTime;
startIndex = list[i].StartTime;
int diff = ((int)(startIndex - endIndex).TotalMinutes);
testList.Add(test[i - 1]);
while (diff >= minBookingLength)
{
nullMarker = new DisplayBookingDetails(0) { Start = endIndex.ToShortTimeString(), End = endIndex.AddMinutes(60).ToShortTimeString() };
testList.Add(nullMarker);
diff -= minBookingLength;
}
}
}
if (test.Length > 0)
testList.Add(test[test.Length - 1]);
DisplayBookingDetails = testList;
}
The code above goes through the array and if it isn't empty it checks the differences between bookings and adds the null marker row in the list, but I would like this display empty rows even if the date has no bookings at all.
Does anyone know how I could go about adding this functionality, thanks?
I'm not sure why you create test instead of using list, but I have completely altered your code to do exactly what you want.
private void CheckForGaps(List<DisplayBookingDetails> list)
{
DateTime endPrevious;
DateTime startCurrent;
int minBookingLength = 60;
DisplayBookingDetails nullMarker = null;
DateTime selectedDate = [CalendarObject].Value.Date;
DateTime dayStart = selectedDate.AddHours(09)
DateTime dayEnd = selectedDate.AddHours(21)
List<DisplayBookingDetails> testList = new List<DisplayBookingDetails>();
if (list.Length > 0) // First we check if the list has any items
{
DateTime startTime = dayStart;
DateTime endTime = list[0].StartTime;
// Fill the gap before the first appointment with blank appointments
while ((endTime - startTime).TotalMinutes >= minBookingLength)
{
nullMarker = new DisplayBookingDetails(0) { Start = startTime.ToShortTimeString(), End = startTime.AddMinutes(minBookingLength).ToShortTimeString() };
testList.Add(nullMarker);
startTime = startTime.AddMinutes(minBookingLength);
}
// Go through the appointments adding them
for (int i = 1; i < list.Length; i++)
{
testList.Add(list[i - 1]);
endPrevious = list[i - 1].EndTime;
startCurrent = list[i].StartTime;
startTime = endPrevious;
// Fill gaps between appointments
while ((startCurrent - startTime).TotalMinutes >= minBookingLength)
{
nullMarker = new DisplayBookingDetails(0) { Start = startTime.ToShortTimeString(), End = startTime.AddMinutes(minBookingLength).ToShortTimeString() };
testList.Add(nullMarker);
startTime = startTime.AddMinutes(minBookingLength);
}
}
// Add the last appointment
testList.Add(list[list.Length - 1]);
// Add blank appointments after the last appointment until End of Day
startTime = list[list.Length - 1].EndTime;
while ((dayEnd - startTime).TotalMinutes >= minBookingLength)
{
nullMarker = new DisplayBookingDetails(0) { Start = startTime.ToShortTimeString(), End = startTime.AddMinutes(minBookingLength).ToShortTimeString() };
testList.Add(nullMarker);
startTime = startTime.AddMinutes(minBookingLength);
}
}
else // No items in list, add all blank appointments
{
DateTime startTime = dayStart;
while((dayEnd - startTime).TotalMinutes >= minBookingLength)
{
nullMarker = new DisplayBookingDetails(0) { Start = startTime.ToShortTimeString(), End = startTime.AddMinutes(minBookingLength).ToShortTimeString() };
testList.Add(nullMarker);
startTime = startTime.AddMinutes(minBookingLength);
}
}
// Display the final list
DisplayBookingDetails.ItemsSource = testList;
}
I am used to linq now and going back to .net 2.0 is a pain.
I need to get the last 12 records by date.I build a noddy sample to explain the problem.I am not happy with the way I coded it. I used reverse on a list to do the job.
Is there a neater way?
here is my code:
class Program
{
private static void Main(string[] args)
{
var allOrders = BuildOrders();
//Reverse so that we can get the orders in date desc and easier to get last 12
allOrders.Reverse();
int count = 0;
List<Order>onlyLast12Orders=new List<Order>();
foreach (Order order in allOrders)
{
count++;
if(count>12)break;
onlyLast12Orders.Add(order);
}
//Reverse again so that it can be displayed in date order
onlyLast12Orders.Reverse();
foreach (Order ord in onlyLast12Orders)
{
Console.WriteLine("Order Name :{0} Date: {1}", ord.Name, ord.Date);
}
Console.Read();
}
private static List<Order> BuildOrders()
{
List<Order> allOrders = new List<Order>();
for (int i = 0; i < 30; i++)
{
Order order = new Order("Order" + i, new DateTime(2013, 1, 1).AddDays(i));
allOrders.Add(order);
}
return allOrders;
}
}
public class Order
{
public Order(string name ,DateTime date)
{
this.name = name;
this.date = date;
}
private string name;
private DateTime date;
public string Name
{
get { return name; }
set { name = value; }
}
public DateTime Date
{
get { return date; }
set { date = value; }
}
}
any suggestions on how to improve the above code to get the last 12 records?
Thanks
You've got a List<Order> - that means you know the count, and the GetRange method.
var allOrders = BuildOrders();
// Take at most 12, but don't try to take more orders than actually exist!
int rangeCount = Math.Min(12, allOrders.Count);
var lastOrders = allOrders.GetRange(allOrders.Count - rangeCount, rangeCount);
You should also consider using LINQBridge - a LINQ to Objects implementation for .NET 2.0.
my optimization will be around while Building The orders , maintain the sort order and then just use one loop to get the number of items.
Stack<Order> is also suitable for such situation:
private static void Main(string[] args)
{
var allOrders = BuildOrders();
Order tempOrder;
for (int i = 0; i < 12; i++)
{
tempOrder = allOrders.Pop();
Console.WriteLine("Order Name :{0} Date: {1}", tempOrder.Name, tempOrder.Date);
if (counter >= 12)
break;
}
}
private static Stack<Order> BuildOrders()
{
Stack<Order> allOrders = new Stack<Order>();
for (int i = 0; i < 30; i++)
{
Order order = new Order("Order" + i, new DateTime(2013, 1, 1).AddDays(i));
allOrders.Push(order);
}
return allOrders;
}
EDIT:
How about this in Main(string[] args):
private static void Main(string[] args)
{
var allOrders = BuildOrders();
Stack<Order> temp = new Stack<Order>();
for (int i = allOrders.Count - 1; i >= allOrders.Count - 12; i--)
{
temp.Push(allOrders[i]);
}
foreach (var order in temp)
{
Console.WriteLine("Order name {0} and date: {1}", order.Name, order.Date);
}
}
You can do all task in one for loop
List<Order> newList = BuildOrders();
List<Order> reverseList = new List<Order>();
for (int i = (newList.Count - 1);
i > ((newList.Count - 1) - 12) && i >= 0; i--)
{
reverseList.Add(newList[i]);
}
So I am currently working on a program in which I need to have a timer attached to each item inside of a list box, I have that working, but I can't select any of the items, is there a way to be able to select the items but also have a timer displayed to each item in the list box?
Update:
when adding the item to a new list box here is the code that I have:
private void btnSchedule_Click(object sender, EventArgs e)
{
try
{
string name = lsbScheduled.SelectedItem.ToString();// saves the selected item to a string
string newItem = (moveItem(name));//calls the method and passes the variable to it
tmrCheckedIn.Enabled = true;
tmrCheckedIn.Start();
newItem += " " + "00:00:00";
lsbScheduled.Items.Remove(name);// removes the item from the list
lsbCheckedIn.Items.Add(newItem); //adds the item to the list
}
catch (NullReferenceException)
{
}
}
here is my code for the tick event:
private void tmrCheckedIn_Tick(object sender, EventArgs e)
{
int count = lsbCheckedIn.Items.Count;
for (int i = 0; i < count; i++)
{
string item = lsbCheckedIn.Items[i].ToString();
string[] line = item.Split();
string time = line[8];
Time oldTime = new Time();
oldTime.StartTime = time;
lsbCheckedIn.Items.Remove(item);
string newTime = string.Format(line[0] + " " + line[1] + " " +line[2] + " " + "{0:c}", oldTime.EndTime);
lsbCheckedIn.Items.Add(newTime);
oldTime = null;
}
}
and here is my class that I use to increase the timer:
public class Time
{
private int seconds, minutes, hours;
string startTime, endTime;
public Time()
{
seconds = 00;
minutes = 00;
hours = 00;
startTime = " ";
endTime = "";
}
public string StartTime
{
set { startTime = value;
CalcNewTime();
}
get { return startTime; }
}
public string EndTime
{
set { endTime = value; }
get { return endTime; }
}
public int Hours
{
set { hours = value; }
get { return hours; }
}
public int Minutes
{
set { minutes = value; }
get { return minutes; }
}
public int Second
{
set { seconds = value; }
get { return seconds; }
}
private void CalcNewTime()
{
const int LIMIT = 6, CONVERT = 10;
string[] divisions = startTime.Split(':');
hours = Convert.ToInt32(divisions[0]);
minutes = Convert.ToInt32(divisions[1]);
seconds = Convert.ToInt32(divisions[2]);
int hoursTens = hours / CONVERT;
int hoursOnes = hours % CONVERT;
int minutesTens = minutes / CONVERT;
int minuteOnes = minutes % CONVERT;
seconds += 1;
int secondTens = seconds / CONVERT;
int secondOnes = seconds % CONVERT;
if (secondTens >= LIMIT)
{
secondTens = 0;
secondOnes = 0;
minutes += 1;
minutesTens = Minutes / CONVERT;
minuteOnes = minutes % CONVERT;
if (minutesTens >= LIMIT)
{
minutesTens = 0;
minuteOnes = 0;
hours += 1;
hoursTens = hours / CONVERT;
hoursOnes = Hours % CONVERT;
}
}
endTime = Convert.ToString(hoursTens + hoursOnes + ":" + minutesTens + minuteOnes + ":" + secondTens + secondOnes);
}
}
in programming a windows form application using visual studio 2010 im using the timer that you can select from the toolbox. I need to be able to select the items in the list box but right now i can because im constantly adding and removing items from the list box. I want the time that is displayed in the list box to go up, but i also need it so that i can select the item in the list box.
Your problem is that you're removing items from the listbox, and then adding new ones. This is why items do not remain selected. Instead, just replace the items.
lsbCheckedIn.Items[i] = newTime;