How can I calculate and display the download speed per file? - c#

private void DownloadFile() {
if (_downloadUrls.Any()) {
WebClient client = new WebClient();
client.DownloadProgressChanged += client_DownloadProgressChanged;
client.DownloadFileCompleted += client_DownloadFileCompleted;
var url = _downloadUrls.Dequeue();
string startTag = "animated/";
string endTag = "/infra";
int index = url.IndexOf(startTag);
int index1 = url.IndexOf(endTag);
string fname = url.Substring(index + 9, index1 - index - 9);
client.DownloadFileAsync(new Uri(url), #"C:\Temp\tempframes\" + fname + ".gif");
lastDownloadedFile = #"C:\Temp\tempframes\" + fname + ".gif";
label1.Text = url;
return;
}
// End of the download
btnStart.Text = "Download Complete";
}
private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) {
if (e.Error != null) {
// handle error scenario
throw e.Error;
}
if (e.Cancelled) {
// handle cancelled scenario
}
Image img = new Bitmap(lastDownloadedFile);
Image[] frames = GetFramesFromAnimatedGIF(img);
foreach(Image image in frames) {
countFrames++;
image.Save(#"C:\Temp\tempframes\" + countFrames + ".gif");
}
DownloadFile();
}
void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) {
double bytesIn = double.Parse(e.BytesReceived.ToString());
double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = bytesIn / totalBytes * 100;
pBarFileProgress.Value = int.Parse(Math.Truncate(percentage).ToString());
label1.Text = e.BytesReceived.ToString() + "/" + e.TotalBytesToReceive.ToString();
}
Now I added this method
DateTime lastUpdate;
long lastBytes = 0;
private void progressChanged(long bytes) {
if (lastBytes == 0) {
lastUpdate = DateTime.Now;
lastBytes = bytes;
return;
}
var now = DateTime.Now;
var timeSpan = now - lastUpdate;
var bytesChange = bytes - lastBytes;
var bytesPerSecond = bytesChange / timeSpan.Seconds;
lastBytes = bytes;
lastUpdate = now;
}
And I want to use this method or another method to display the download speed in the progresschanged event on label2. But I'm not sure how to use this method.
Not sure how to use with it in the progresschanged event.

The call to your prepared method progressChanged would best fit into client_DownloadProgressChanged like this:
progressChanged(e.BytesReceived);
You must however use TotalSeconds instead of Seconds or the values will not be correct and also cause a division by zero exception
var bytesPerSecond = bytesChange / timeSpan.TotalSeconds;
This helper class will keep track of received chunks, timestamps and progress for you:
public class DownloadProgressTracker
{
private long _totalFileSize;
private readonly int _sampleSize;
private readonly TimeSpan _valueDelay;
private DateTime _lastUpdateCalculated;
private long _previousProgress;
private double _cachedSpeed;
private Queue<Tuple<DateTime, long>> _changes = new Queue<Tuple<DateTime, long>>();
public DownloadProgressTracker(int sampleSize, TimeSpan valueDelay)
{
_lastUpdateCalculated = DateTime.Now;
_sampleSize = sampleSize;
_valueDelay = valueDelay;
}
public void NewFile()
{
_previousProgress = 0;
}
public void SetProgress(long bytesReceived, long totalBytesToReceive)
{
_totalFileSize = totalBytesToReceive;
long diff = bytesReceived - _previousProgress;
if (diff <= 0)
return;
_previousProgress = bytesReceived;
_changes.Enqueue(new Tuple<DateTime, long>(DateTime.Now, diff));
while (_changes.Count > _sampleSize)
_changes.Dequeue();
}
public double GetProgress()
{
return _previousProgress / (double) _totalFileSize;
}
public string GetProgressString()
{
return String.Format("{0:P0}", GetProgress());
}
public string GetBytesPerSecondString()
{
double speed = GetBytesPerSecond();
var prefix = new[] { "", "K", "M", "G"};
int index = 0;
while (speed > 1024 && index < prefix.Length - 1)
{
speed /= 1024;
index++;
}
int intLen = ((int) speed).ToString().Length;
int decimals = 3 - intLen;
if (decimals < 0)
decimals = 0;
string format = String.Format("{{0:F{0}}}", decimals) + "{1}B/s";
return String.Format(format, speed, prefix[index]);
}
public double GetBytesPerSecond()
{
if (DateTime.Now >= _lastUpdateCalculated + _valueDelay)
{
_lastUpdateCalculated = DateTime.Now;
_cachedSpeed = GetRateInternal();
}
return _cachedSpeed;
}
private double GetRateInternal()
{
if (_changes.Count == 0)
return 0;
TimeSpan timespan = _changes.Last().Item1 - _changes.First().Item1;
long bytes = _changes.Sum(t => t.Item2);
double rate = bytes / timespan.TotalSeconds;
if (double.IsInfinity(rate) || double.IsNaN(rate))
return 0;
return rate;
}
}
In the following example, the progress tracker will give you the average download rate of the last 50 received Packets but only every 500 ms (so the UI doesn't flicker). You might need to tinker with the values a bit to find a good balance between accuracy and smoothness.
//Somewhere in your constructor / initializer:
tracker = new DownloadProgressTracker(50, TimeSpan.FromMilliseconds(500));
void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
tracker.SetProgress(e.BytesReceived, e.TotalBytesToReceive);
pBarFileProgress.Value = tracker.GetProgress() * 100;
label1.Text = e.BytesReceived + "/" + e.TotalBytesToReceive;
label2.Text = tracker.GetBytesPerSecondString();
}
Keep in mind, that you have to reset the tracker before or after every new file:
tracker.NewFile();
In case you need some bigger files to test this with, I've found some here

Related

How do I know what file have been downloaded in the completed event?

private async void BtnDownloadFile_Click(object sender, RoutedEventArgs e)
{
btnDownloadFile.IsEnabled = false; // Disable to prevent multiple runs
using (System.Net.WebClient wc = new System.Net.WebClient())
{
wc.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36");
wc.DownloadProgressChanged += OnDownloadProgressChange;
wc.DownloadFileCompleted += OnDownloadFileComplete;
stopwatch.Start();
await DownloadAsync(wc);
}
}
private void OnDownloadProgressChange(object sender, System.Net.DownloadProgressChangedEventArgs e)
{
// Calculate progress values
string downloadProgress = e.ProgressPercentage + "%";
string downloadSpeed = string.Format("{0} MB/s", (e.BytesReceived / 1024.0 / 1024.0 / stopwatch.Elapsed.TotalSeconds).ToString("0.00"));
string downloadedMBs = Math.Round(e.BytesReceived / 1024.0 / 1024.0) + " MB";
string totalMBs = Math.Round(e.TotalBytesToReceive / 1024.0 / 1024.0) + " MB";
// Format progress string
string progress = $"{downloadedMBs}/{totalMBs} ({downloadProgress}) # {downloadSpeed}"; // 10 MB / 100 MB (10%) # 1.23 MB/s
// Set values to contols
lblProgress.Content = progress;
progBar.Value = e.ProgressPercentage;
}
private async void OnDownloadFileComplete(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
lblProgress.Content = "Download complete!";
stopwatch.Reset();
btnDownloadFile.IsEnabled = true;
if(e.Error == null)
{
urlsCounter--;
lblMumberOfFiles.Content = urlsCounter;
if (e.UserState.ToString().Contains("Radar"))
{
drawonimage.DrawText(datesonimages[0].ToString(), #"d:\Downloaded Images\Radar\radImage6.gif");
}
}
if (extractOnce == false)
{
radar.GetRadarImages();
await Task.Delay(5000);
for (int i = 0; i < radar.links.Count; i++)
{
urls.Add(radar.links[i]);
}
dates = radar.dates;
foreach(var date in dates)
{
datesonimages.Add(date.ToString("ddd, dd MMM yyy HH':'mm"));
}
ExtractLinks();
extractOnce = true;
}
}
In the OnDownloadFileComplete event I want to know what file have been downloaded fine without any errors and then do some manipulation/s on this image file.
When downloading the images at this method I know if the file is Radar or not :
But the manipulation I want to do for the images is when they are downloaded each "Radar" that have been success downloaded I want to do something with that image from the hard disk in the OnDownloadFileComplete event. I'm not sure how to find the "Radar" each downloaded image file in the OnDownloadFileComplete event.
int countRad = 0;
int countSat = 0;
private async Task DownloadAsync(WebClient Client)
{
for (int i = 0; i < urls.Count; i++)
{
stopwatch.Start();
string extractFile = textBoxSatelliteFolder.Text + "\\extractFile.txt";
string fNameRad = textBoxRadarFolder.Text + "\\radImage" + countRad + ".gif";
string fNameSat = textBoxSatelliteFolder.Text + "\\satImage" + countSat + ".gif";
if (urls[i] == "https://myimage.com/")
{
await Client.DownloadFileTaskAsync(new Uri(urls[i]), extractFile);
}
else
{
if (urls[i].Contains("Radar"))
{
await Client.DownloadFileTaskAsync(new Uri(urls[i]), fNameRad);
countRad++;
}
else
{
await Client.DownloadFileTaskAsync(new Uri(urls[i]), fNameSat);
countSat++;
}
}
}
}

No syntax errors, but program does not produce any results

I have to create a program for class. My applications needs to have value returning methods for OilLubeCharges(), FlushCharges(), MiscCharges(), OtherCharges(), TaxCharges(), TotalCharges().
It needs to have void methods for ClearOilLube(), ClearFlushes(), ClearMisc(), ClearOther(), ClearFees().
Currently my code has no syntax errors, however when I compile it it does not calculate anything. The calculate, clear, and exit buttons also do not work. Any assistance as to why these issues are occurring would be appreciated. Below is my code.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void CalcButton_Click(object sender, EventArgs e)
{
OilLubeCharges();
FlushCharges();
MiscCharges();
OtherCharges();
TaxCharges();
TotalCharges();
}
private void ClearButton_Click(object sender, EventArgs e)
{
oilCheckBox.Checked = false;
lubeCheckBox.Checked = false;
radFlushBox.Checked = false;
tranFlushBox.Checked = false;
insCheckBox.Checked = false;
mufCheckBox.Checked = false;
tireCheckBox.Checked = false;
partsTextBox.Text = "";
laborTextBox.Text = "";
serLabTotalTextBox.Text = "";
partsTotalTextBox.Text = "";
taxPartsTextBox.Text = "";
totalFeesTextBox.Text = "";
}
private void ExitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private int OilLubeCharges()
{
int total = 0;
if (oilCheckBox.Checked)
{
total += 26;
serLabTotalTextBox.Text = total.ToString("c");
}
if (lubeCheckBox.Checked)
{
total += 18;
serLabTotalTextBox.Text = total.ToString("c");
return total;
}
else
{
return total;
}
}
private int FlushCharges()
{
int total = 0;
if (radFlushBox.Checked)
{
total += 30;
serLabTotalTextBox.Text = total.ToString("c");
}
if (tranFlushBox.Checked)
{
total += 80;
serLabTotalTextBox.Text = total.ToString("c");
return total;
}
else
{
return total;
}
}
private int MiscCharges()
{
int total = 0;
if (insCheckBox.Checked)
{
total += 15;
serLabTotalTextBox.Text = total.ToString("c");
}
if (mufCheckBox.Checked)
{
total += 100;
serLabTotalTextBox.Text = total.ToString("c");
}
if (tireCheckBox.Checked)
{
total += 20;
serLabTotalTextBox.Text = total.ToString("c");
return total;
}
else
{
return total;
}
}
private int OtherCharges()
{
int total = 0;
int parts = 0;
int labor = 0;
if (int.TryParse(partsTextBox.Text, out parts))
{
partsTextBox.Text = parts.ToString("c");
total = parts;
}
if (int.TryParse(laborTextBox.Text, out labor))
{
laborTextBox.Text = labor.ToString("c");
return total;
}
else
{
return total;
}
}
private decimal TaxCharges()
{
decimal parts = 0;
decimal partsTax;
partsTax = parts * .06m;
taxPartsTextBox.Text = partsTax.ToString("c");
return partsTax;
}
private decimal TotalCharges()
{
decimal total = 0;
total = OilLubeCharges() + FlushCharges() + MiscCharges() + TaxCharges() + OtherCharges();
totalFeesTextBox.Text = total.ToString("c");
return total;
}
}
As stated in the comments above, most likely your events are not hooked up to your buttons. You can do this several ways; typically it's done in the designer.
To know for sure if this is the cause, try this:
public Form1()
{
InitializeComponent();
CalcButton.Click += CalcButton_Click;
}
Note that this assumes your button is named "CalcButton". You can see whether that's true in the designer as well.
If that works, you need to do the same with the rest of your buttons either the same way or by selecting the method in the designer for the button.

How to convert Listview dates to local time zone?

I have 3 columns in the ListView. From,Subject,Date
I'm using the OpenPop library.
private int numberofallmessages = 0;
private int countMsg = 0;
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
OpenPop.Pop3.Pop3Client PopClient = new OpenPop.Pop3.Pop3Client();
PopClient.Connect("mail", 110, false);
PopClient.Authenticate("me", "me",
OpenPop.Pop3.AuthenticationMethod.UsernameAndPassword);
List<string> uids = PopClient.GetMessageUids();
int messageCount = PopClient.GetMessageCount() -1;
numberofallmessages = messageCount;
allMessages = new List<OpenPop.Mime.Message>(messageCount);
for (int i = messageCount; i > 0; i--)//for (int i = messageCount - 1; i > -1; i--)
{
if (backgroundWorker1.CancellationPending == true)
{
e.Cancel = true;
return;
}
string currentUidOnServer = uids[i];
if (!seenUids.Contains(currentUidOnServer))
{
if (i > 0)
allMessages.Add(PopClient.GetMessage(i));
SaveFullMessage(PopClient.GetMessage(i), i);
w = new StreamWriter(emailsIDSFile, true);
w.WriteLine(currentUidOnServer);
w.Close();
int nProgress = (messageCount - i + 1) * 100 / messageCount;
backgroundWorker1.ReportProgress(nProgress, PopClient.GetMessageCount().ToString() + "/" + i);
}
}
PopClient.Disconnect();
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
pbt.Value = e.ProgressPercentage;
pbt.Text = e.ProgressPercentage.ToString() + "%";
pbt.Invalidate();
label8.Text = e.UserState.ToString();
label8.Visible = true;
lvnf.Items.Add(new ListViewItem(new string[]
{
allMessages[countMsg].Headers.From.ToString(), //From Column
allMessages[countMsg].Headers.Subject, //Subject Column
allMessages[countMsg].Headers.DateSent.ToString() //Date Column
}));
countMsg += 1;
}
The problem is in the progresschanged event i think. Where i add the items to each column.
When it's adding the emails to the ListView i see it like this:
The problem is on the date column the date is fine but the time in not my time. Not sure of what place the time is but in my place it's now 1:52 AM
How can i get/set the time of my place ?
I couldn't find in the line:
allMessages[countMsg].Headers.DateSent.ToString()
How to change it to my time.
Try this:
allMessages[countMsg].Headers.DateSent.ToLocalTime().ToString();
You want to utilize the DateTime.ToLocalTime() method. It does the heavy lifting for you.
Hope this helps
Edit: Removed incorrect version as the documentation for OpenPop.Net states that the MessageHeader.DateSent property is in fact a DateTime object.

Exception when trying to close serial port or exít application

I have an application that reads XBee frames through the serial port and displays the frame in a richtextbox. It also displays the 2 analog channels (temperature Readings) in a chart and updates it in real time.
I was having issues that the application was reading the serial port faster than the bytes were coming in so I added this line:
while (comPort.BytesToRead < (inLength + 4)) Thread.Sleep(10);
That solved that problem but now I am unable to Close the serial port or quit the application without getting the message: "An unhandled exception of type 'System.InvalidOperationException' occurred in System.dll Additional information: The port is closed."
I am suspicious that it is a multithreading issue, but how do I solve it? I saw on a similar post that using BeginInvoke instead of Invoke should resolve the issue, but I am already using that.
Here is the code:
namespace SerialTest
{
public partial class frmMain : Form
{
delegate void SetTextCallback(string text);
delegate void SetChartCallback(double a, double b);
string inRawFrame = String.Empty;
double temp1 = 0;
double temp2 = 0;
public frmMain()
{
InitializeComponent();
}
private void btnGetSerialPorts_Click(object sender, EventArgs e)
{
if(btnGetSerialPorts.Text == "Open")
{
btnGetSerialPorts.Text = "Close";
comPort.PortName = Convert.ToString(cboPorts.Text);
comPort.BaudRate = Convert.ToInt32(cboBaudRate.Text);
comPort.ReadTimeout = 4000;
comPort.WriteTimeout = 6000;
if (!comPort.IsOpen)
{
try
{
comPort.Open();
cboPorts.Enabled = false;
cboBaudRate.Enabled = false;
}
catch(UnauthorizedAccessException ex)
{
MessageBox.Show(ex.Message);
}
}
}
else if (btnGetSerialPorts.Text == "Close")
{
btnGetSerialPorts.Text = "Open";
comPort.Close();
cboPorts.Enabled = true;
cboBaudRate.Enabled = true;
}
}
private void Form1_Load(object sender, EventArgs e)
{
string[] arrayComPortsNames = null;
int index = 0;
string comPortName = null;
arrayComPortsNames = SerialPort.GetPortNames();
Array.Sort(arrayComPortsNames);
while (!((arrayComPortsNames[index] == comPortName) || (index == arrayComPortsNames.GetUpperBound(0))))
{
cboPorts.Items.Add(arrayComPortsNames[index]);
index++;
}
comPortName = arrayComPortsNames[0];
cboPorts.Text = comPortName;
cboBaudRate.Items.Add(9600);
cboBaudRate.Items.Add(14400);
cboBaudRate.Items.Add(19200);
cboBaudRate.Items.Add(38400);
cboBaudRate.Items.Add(57600);
cboBaudRate.Items.Add(115200);
cboBaudRate.Items.ToString();
cboBaudRate.Text = cboBaudRate.Items[5].ToString();
}
private void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
byte[] incByte = new byte[3];
int length = 0;
if(comPort.BytesToRead > 3)
{
comPort.Read(incByte, 0, 3);
if (incByte[0] == 0x7E)
{
length = (incByte[1] << 8) + incByte[2];
byte[] buffer = new byte[length+4];
buffer[0] = incByte[0];
buffer[1] = incByte[1];
buffer[2] = incByte[2];
ReadFrame(buffer, length, DateTime.Now);
temp1 = ReadTemp(buffer, 1);
temp2 = ReadTemp(buffer, 2);
DisplayFrame();
UpdateChart();
}
}
}
private void ReadFrame(byte[] inBuffer, int inLength, DateTime time)
{
while (comPort.BytesToRead < (inLength + 4)) Thread.Sleep(10);
comPort.Read(inBuffer, 3, (inBuffer.Length - 3));
inRawFrame = time + " " + BitConverter.ToString(inBuffer).Replace("-", " ");
}
private void DisplayFrame()
{
if (rtbIncomingData.InvokeRequired)
{
rtbIncomingData.BeginInvoke(new SetTextCallback(SetText), new object[] { inRawFrame });
}
else
{
SetText(inRawFrame);
}
}
private void SetText(string text)
{
this.rtbIncomingData.AppendText(text + Environment.NewLine);
}
private double ReadTemp(byte[] data, int channel)
{
if(data[3] == 0x92)
{
if(channel == 1)
{
return ((((data[19] << 8) + data[20]) * 1.2 / 1023) - 0.5) * 100.0;
}
else
{
return ((((data[21] << 8) + data[22]) * 1.2 / 1023) - 0.5) * 100.0;
}
}
else
return 100;
}
private void UpdateChart()
{
if (chart1.InvokeRequired)
chart1.BeginInvoke(new SetChartCallback(SetChart), new object[] { temp1, temp2 });
else
SetChart(temp1, temp2);
}
private void SetChart(double val1, double val2)
{
chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.Format = "HH:mm:ss";
chart1.ChartAreas["ChartArea1"].AxisX.MajorGrid.LineColor = Color.LightGray;
chart1.ChartAreas["ChartArea1"].AxisY.MajorGrid.LineColor = Color.LightGray;
chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.Font = new Font("Consolas", 8);
chart1.ChartAreas["ChartArea1"].AxisY.LabelStyle.Font = new Font("Consolas", 8);
chart1.ChartAreas["ChartArea1"].AxisY.Maximum = 30;
chart1.ChartAreas["ChartArea1"].AxisY.Minimum = 10;
chart1.ChartAreas["ChartArea1"].AxisY.Interval = 1;
chart1.Series[0].Name = "Temp 1";
chart1.Series[1].Name = "Temp 2";
chart1.Series[0].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
chart1.Series[0].MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Diamond;
chart1.Series[0].XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.DateTime;
chart1.Series[1].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
chart1.Series[1].MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Diamond;
chart1.Series[1].XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.DateTime;
chart1.Series[0].Points.AddXY(DateTime.Now, val1);
chart1.Series[1].Points.AddXY(DateTime.Now, val2);
}
}
}
If you close the serial port while ReadFrame() is still waiting for bytes, you'll end up checking BytesToRead on a closed serial port. Maybe try this version instead:
private void ReadFrame(byte[] inBuffer, int inLength, DateTime time)
{
while (comPort.IsOpen)
{
if (comPort.BytestoRead >= inLength + 4)
{
comPort.Read(inBuffer, 3, (inBuffer.Length - 3));
inRawFrame = time + " " + BitConverter.ToString(inBuffer).Replace("-", " ");
return;
}
Thread.Sleep(10);
}
}
It will exit if the serial port closes while waiting for a frame, and only checks BytesToRead if the port is still open.

Timer inside a listbox c#

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;

Categories

Resources