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
}
Related
Background information
Just starting out to learn C#, im trying to build a simple web app that calculate the no of working day(s) between 2 dates.
The UI of the web app
The basic logic is when the user input a date (ie 01/05/2018) and click the button.It will calculate the total number of working day (exclude weekends and public holidays).
The problem now is the calculation isnt accurate ie between 23/05/2018 & 31/05/2018 it shows 6, it should be 7 days. And it doesnt take the dates into consideration during calculation
namespace testtest
{
public partial class First : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
//on btn click
protected void Button1_Click(object sender, EventArgs e)
{
string dt = TextBox1.Text;
DateTime dtDDMMYYYY = ParseDate(dt);
string dt2 = TextBox2.Text;
DateTime dtDDMMYYYY2 = ParseDate(dt2);
List<DateTime> list = new List<DateTime> {
DateTime.ParseExact("04/05/2018", "dd/MM/yyyy",
CultureInfo.InvariantCulture) };
DaysLeft(dtDDMMYYYY, dtDDMMYYYY2, true, list);
}
public DateTime ParseDate(string date)
{
DateTimeFormatInfo dateFormatProvider = new DateTimeFormatInfo();
dateFormatProvider.ShortDatePattern = "dd/MM/yyyy";
return DateTime.Parse(date, dateFormatProvider);
}
public int DaysLeft(DateTime startDate, DateTime endDate, Boolean
excludeWeekends, List<DateTime> excludeDates)
{
int count = 0;
for (DateTime index = startDate; index < endDate; index =
index.AddDays(1))
{
if (excludeWeekends && index.DayOfWeek != DayOfWeek.Sunday &&
index.DayOfWeek != DayOfWeek.Saturday)
{
bool excluded = false; ;
for (int i = 0; i < excludeDates.Count; i++)
{
if (index.Date.CompareTo(excludeDates[i].Date) == 0)
{
excluded = true;
break;
}
}
if (!excluded)
{
count++;
}
}
}
result.Text = count.ToString();
return count;
}
}
}
Keep it simple
public int DaysLeft(DateTime startDate, DateTime endDate, Boolean excludeWeekends, List<DateTime> excludeDates) {
int count = 0;
for (DateTime index = startDate; index <= endDate; index = index.AddDays(1)) {
if (excludeWeekends && (index.DayOfWeek == DayOfWeek.Sunday || index.DayOfWeek == DayOfWeek.Saturday))
continue;
if (excludeDates.Contains(index.Date))
continue;
count++;
}
return count;
}
If the date is a weekend and excludeWeekends flagged, continue on to next date, if date is included in excludeDates continue, else count the day.
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);
I've been assigned with the task of calculating a time difference only counting working hours. After searching I was able to get this (it's kinda in Portuguese but I think it's understandable) :
if (!txt_data2.Text.Contains("_") && !string.IsNullOrEmpty(txt_data2.Text) && txt_data2.Text != null && !txt_hora2.Text.Contains("_") && !string.IsNullOrEmpty(txt_hora2.Text) && txt_hora2.Text != null)
{
TimeSpan hi = TimeSpan.Parse(txt_horainicio.Text);
TimeSpan hf = TimeSpan.Parse(txt_hora2.Text);
if (hi.Hours < 9 || hf.Hours > 18)
{
MessageBox.Show("Horas Inválidas");
}
else
{
if (MessageBox.Show("Inserir horas extraordinárias?", "Horas Extraordinárias", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
{
double extra;
TimeSpan horasextra;
Frm_Tempo frm1 = new Frm_Tempo();
if (frm1.ShowDialog() == DialogResult.OK)
{
horasextra = TimeSpan.Parse(frm1.txt_horasextra.Text);
extra = horasextra.TotalHours;
DateTime data1 = Convert.ToDateTime(txt_datainicio.Text);
TimeSpan hora1 = TimeSpan.Parse(txt_horainicio.Text);
DateTime dataentrega1 = Convert.ToDateTime(txt_data2.Text);
TimeSpan horaentrega1 = TimeSpan.Parse(txt_hora2.Text);
data1 = data1.Add(hora1);
dataentrega1 = dataentrega1.Add(horaentrega1);
double horas1 = 0;
double minutos1 = 0;
for (var i = data1; i < dataentrega1; i = i.AddMinutes(1))
{
if (i.DayOfWeek != DayOfWeek.Saturday && i.DayOfWeek != DayOfWeek.Sunday)
{
if (i.TimeOfDay.Hours >= 9 && i.TimeOfDay.Hours <= 18)
{
if (i.TimeOfDay.Hours >= 13 && i.TimeOfDay.Hours < 14)
{
}
else
{
minutos1++;
for (var x = data1; x < dataentrega1; x = x.AddHours(1))
{
horas1 = (minutos1 / 60) + extra;
}
}
}
}
}
TimeSpan tempo1 = TimeSpan.FromHours(horas1);
MySqlCommand UPDATE20 = new MySqlCommand("UPDATE tbl_orcamentos SET tempo ='" + tempo1 + "'WHERE id ='" + txt_cod.Text + "'", ligar);
UPDATE20.ExecuteNonQuery();
}
}
else
{
DateTime data = Convert.ToDateTime(txt_datainicio.Text);
TimeSpan hora = TimeSpan.Parse(txt_horainicio.Text);
DateTime dataentrega = Convert.ToDateTime(txt_data2.Text);
TimeSpan horaentrega = TimeSpan.Parse(txt_hora2.Text);
data = data.Add(hora);
dataentrega = dataentrega.Add(horaentrega);
float horas = 0;
float minutos = 0;
for (var i = data; i < dataentrega; i = i.AddMinutes(1))
{
if (i.DayOfWeek != DayOfWeek.Saturday && i.DayOfWeek != DayOfWeek.Sunday)
{
if (i.TimeOfDay.Hours >= 9 && i.TimeOfDay.Hours < 18)
{
if (i.TimeOfDay.Hours >= 13 && i.TimeOfDay.Hours < 14)
{
}
else
{
minutos++;
for (var x = data; x < dataentrega; x = x.AddHours(1))
{
horas = minutos / 60;
}
}
}
}
}
TimeSpan tempo = TimeSpan.FromHours(horas);
MySqlCommand UPDATE21 = new MySqlCommand("UPDATE tbl_orcamentos SET tempo ='" + tempo + "'WHERE id ='" + txt_cod.Text + "'", ligar);
UPDATE21.ExecuteNonQuery();
}
}
}
I'm using c# and a mysql database.
It seems to work but when the result was 48h, instead of "48:00:00", it's trying to update it to "2.00:00:00" which isn't valid as "tempo" it's a time field in mysql. I don't really know how to solve it and so far I've tried to make "horas" a datetime and then formatting it to the right format but it didn't work.
I'd really appreciate any help and I'm sorry if it's hard to understand, just ask and I'll try to explain further.
EDIT:
Adding the float "horas" which contains the number of hours into the Timespan:
TimeSpan tempo = TimeSpan.FromHours(horas);
The standard SQL data type for a difference in time is "interval". MySQL doesn't support the "interval" data type.
It can be confusing, because times of day and intervals use the same notation, but have different meanings. The value '1:00' means 1 o'clock if it's a time of day ("time" or "timestamp"). But the same value means one hour if it's an interval.
Also, "48:00:00" is a valid interval (48 hours), but it's not a valid time of day.
If you're using MySQL, calculate and store the interval in an integer representing the number of hours, minutes, or seconds, and format for display. For example, store two hours as the integer 7200 (seconds) or as the integer 120 (minutes), depending on the application's requirements. Format that integer as "2:00" for display. C#'s TimeSpan.FromMinutes and TimeSpan.FromSeconds will help.
If you want to play around with an open source dbms that supports intervals, look at PostgreSQL.
My teacher told me to select columndate cocat columntime as column3, then parse column3 as datetime datatype. He says I can't change the database datatype and I need to use those 4 column field start_date, end_date, start_time and end_time as it's in a server so he told me to do this.
He meant to combine start_date field and start_time field as one column in the code, then convert it to datetime type also done in the code. Same goes for end date field and end_time field. That means for example, start_date and start_time for record 1 will become 3/4/2014 9:00:00AM, end_date and end_time for record 1 will become to 3/4/2014 12:00:00PM.
so below are my codes, it's for a scheduler/timetable, which is called daypilot. So can help me in the query for the converting? in the code below there is a start_date and end_date, that is to be replaced by the datetime datatype that is finally parsed. help man
MY SCHEDULE TABLE
MY DAYPILOT CONTROL PROPERTIES
IDEAL OUTPUT IF CODE WORKS... THIS IS WHAT I WANT TO ACHIEVE. I have test this using two datetime column in a table which works.
public partial class number2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DayPilotCalendar1.StartDate = DayPilot.Utils.Week.FirstWorkingDayOfWeek(new DateTime(2014, 03, 24));
DayPilotCalendar1.DataSource = dbGetEvents(DayPilotCalendar1.StartDate, DayPilotCalendar1.Days);
DataBind();
}
}
private DataTable dbGetEvents(DateTime start, int days)
{
string constr = ConfigurationManager.ConnectionStrings["ProjectConnectionString"].ConnectionString;
SqlDataAdapter da = new SqlDataAdapter("SELECT ID, PURPOSE, [START_DATE], [END_DATE] FROM [Schedule] WHERE NOT (([END_DATE] <= #start) OR ([START_DATE] >= #end))", constr);
da.SelectCommand.Parameters.AddWithValue("start", start);
da.SelectCommand.Parameters.AddWithValue("end", start.AddDays(days));
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
following #Trafz codes and it worked. this is the answer.
public partial class number2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DayPilotCalendar1.StartDate = DayPilot.Utils.Week.FirstWorkingDayOfWeek(new DateTime(2014, 04, 03));
//DayPilotCalendar1.StartDate = DayPilot.Utils.Week.FirstWorkingDayOfWeek(DateTime.Now.AddDays(-(int)DateTime.Now.DayOfWeek).Date);
DayPilotCalendar1.DataSource = dbGetEvents(DayPilotCalendar1.StartDate, DayPilotCalendar1.Days);
DataBind();
}
}
private DataTable dbGetEvents(DateTime start, int days)
{
string constr = ConfigurationManager.ConnectionStrings["ProjectConnectionString"].ConnectionString;
SqlDataAdapter da = new SqlDataAdapter("SELECT ID, PURPOSE, [START_DATE], [END_DATE], [START_TIME], [END_TIME] FROM [Schedule]", constr);
da.SelectCommand.Parameters.AddWithValue("start", start);
da.SelectCommand.Parameters.AddWithValue("end", start.AddDays(days));
DataTable dt = new DataTable();
da.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
dt.Rows[i]["START_DATE"] = CombineDateAndTime(dt.Rows[i]["START_DATE"], dt.Rows[i]["START_TIME"]);
dt.Rows[i]["END_DATE"] = CombineDateAndTime(dt.Rows[i]["END_DATE"], dt.Rows[i]["END_TIME"]);
}
return dt;
}
public static DateTime CombineDateAndTime(object date, object time)
{
if (date == null)
{
// Add some logic for this scenario. Here are 2 examples:
//throw new ArgumentNullException("date");
//date = DateTime.MaxValue;
}
if (time == null)
{
// Add some logic for this scenario.
//throw new ArgumentNullException("time");
//time = 0;
}
DateTime dt = Convert.ToDateTime(date);
float hoursAndMinutes = Convert.ToInt32(time);
return CombineDateAndTime(dt, hoursAndMinutes);
}
public static DateTime CombineDateAndTime(DateTime date, float time)
{
int hours = Convert.ToInt32(Math.Round((decimal)time / 100, MidpointRounding.AwayFromZero));
float remainder = time - (hours * 100);
int minutes = Convert.ToInt32(Math.Round((decimal)remainder, MidpointRounding.AwayFromZero));
DateTime returnDate = date.Date.AddHours(hours).AddMinutes(minutes);
return returnDate;
}
}
After you do this: da.Fill(dt);, you can to alter the data it received.
Here's a code-snippet of how I think you COULD combine your 2 columns into 1 DateTime:
public static void JustSomeMethodToTestTheConvertion()
{
DateTime date = DateTime.Now.Date;
float time = 900;
DateTime concatDate = CombineDateAndTime(date, time);
Console.WriteLine(concatDate);
}
public static DateTime CombineDateAndTime(DateTime date, float time)
{
int hours = Convert.ToInt32(Math.Round((decimal)time / 100, MidpointRounding.AwayFromZero));
float remainder = time - (hours * 100);
int minutes = Convert.ToInt32(Math.Round((decimal)remainder, MidpointRounding.AwayFromZero));
return date.AddHours(hours).AddMinutes(minutes);
}
So you would need to loop through your data and do something like this and then fill it in.
To reply to your comment:
private DataTable dbGetEvents(DateTime start, int days)
{
string constr = ConfigurationManager.ConnectionStrings["ProjectConnectionString"].ConnectionString;
SqlDataAdapter da = new SqlDataAdapter("SELECT ID, PURPOSE, [START_DATE], [END_DATE] FROM [Schedule] WHERE NOT (([END_DATE] <= #start) OR ([START_DATE] >= #end))", constr);
da.SelectCommand.Parameters.AddWithValue("start", start);
da.SelectCommand.Parameters.AddWithValue("end", start.AddDays(days));
DataTable dt = new DataTable();
da.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
dt.Rows[i]["YourConcatDateColumn"] = CombineDateAndTime(dt.Rows[i]["Date"], dt.Rows[i]["Time"]);
}
return dt;
}
public static DateTime CombineDateAndTime(object date, object time)
{
if (date == null)
{
// Add some logic for this scenario. Here are 2 examples:
//throw new ArgumentNullException("date");
//date = DateTime.MaxValue;
}
if (time == null)
{
// Add some logic for this scenario.
//throw new ArgumentNullException("time");
//time = 0;
}
DateTime dt = Convert.ToDateTime(date);
float hoursAndMinutes = Convert.ToInt32(time);
return CombineDateAndTime(dt, hoursAndMinutes);
}
public static DateTime CombineDateAndTime(DateTime date, float time)
{
int hours = Convert.ToInt32(Math.Round((decimal)time / 100, MidpointRounding.AwayFromZero));
float remainder = time - (hours * 100);
int minutes = Convert.ToInt32(Math.Round((decimal)remainder, MidpointRounding.AwayFromZero));
DateTime returnDate = date.Date.AddHours(hours).AddMinutes(minutes);
return returnDate;
}
But you would need to SELECT all of the needed columns and also change the "YourConcatDateColumn" parts to the name of the proper columns to use. E.g. ["START_DATE"] and ["START_TIME"].
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;