Date/Time Picker unable to loop properly - c#

Want to do a loop of picture slideshow to start from a specific time and then to end at another specific time.
Also, how to set the DateTime picker to select minutes/hours?
//Under start button
if (rbtnDateTime.Checked == true)
{
DateTime startDate = dateTimePicker1.Value.Date;
DateTime stopDate = dateTimePicker2.Value.Date;
//Given time interval in seconds
if (mtxtSlideShowInterval.Text != "")
{
int interval = Convert.ToInt16(mtxtSlideShowInterval.Text);
while ((startDate = startDate.AddSeconds(interval)) <= stopDate)
{
timerSlideShow.Enabled = true;
timerSlideShow.Start();
}
timerSlideShow.Stop();
timerSlideShow.Enabled = false;
}
}
//Under timer_tick event
//Infinite Loop
else
{
if (listBoxPicturesInAlbum.SelectedIndex ==listBoxPicturesInAlbum.Items.Count - 1)
{
listBoxPicturesInAlbum.SelectedIndex = 0;
}
else
{
listBoxPicturesInAlbum.SelectedIndex++;
}
}

I would be rid of the while loop you have, and take a few steps.
First, you'll need a field to mark your current index:
int currentImageIndex = 0;
Second, you'll set your timer.Interval.
timer.Interval = int.Parse(mtxtSlideShowInterval.Text) * 1000;
Third, your timer_tick can include something like this:
if (DateTime.Now < dateTimePicker2.Value.Date)
{
listBoxPicturesInAlbum.SelectedIndex = currentImageIndex;
pictureBox.Image = Image.FromFile((string)listBoxPicturesInAlbum.SelectedValue);
currentImageIndex = (currentImageIndex + 1) % listBoxPicturesInAlbum.Items.Count;
}

Related

Timer Goes Negative

I am facing an issue with my timer. The issue is, timer goes negative after reaching the specified time limit and the next levels never unlocks. This only happens whenever I change my timespan to 24 hours. When I am using seconds or minutes the timer stops when it reaches to zero (0) and make the button interactable again. I have also tested it on 1 hour and it works fine.
IEnumerator TimeUpdate()
{
if (bonus != null)
{
if (PlayerPrefs.GetInt("Bonus", 0) == 0)
{
bonus.interactable = true;
showTimer.gameObject.SetActive(false);
PlayerPrefs.SetString("BONUS_END_TIME", "");
StopAllCoroutines();
}
else
{
bonus.interactable = false;
showTimer.gameObject.SetActive(true);
}
}
while (true)
{
chkbonustime();
DateTime dt = DateTime.Now;
string bonusendtime = PlayerPrefs.GetString("BONUS_END_TIME", "");
DateTime dateComplete;
if (bonusendtime != null)
{
dateComplete = DateTime.Parse(bonusendtime);
DateTime ENDTIME = dateComplete.Add(TimeSpan.FromHours(24));
TimeSpan ABC = ENDTIME - dt;
showTimer.text = ABC.Hours + " : " + ABC.Minutes + " : " + ABC.Seconds;
}
// Debug.Log();
yield return new WaitForSeconds(1);
}
}
public void chkbonustime()
{
string bonusendtime = PlayerPrefs.GetString("BONUS_END_TIME", "");
if (!bonusendtime.Equals(""))
{
DateTime dateComplete = DateTime.Parse(bonusendtime);
DateTime xyz = DateTime.Now;
TimeSpan timespan = xyz - dateComplete;
Debug.Log(timespan.Seconds);
if (timespan.Hours >= 24)
{
// if (PlayerPrefs.GetInt("Bonus", 0) == 1)
// {
PlayerPrefs.SetInt("Bonus", 0);
bonus.interactable = true;
showTimer.gameObject.SetActive(false);
PlayerPrefs.SetString("BONUS_END_TIME", "");
StopAllCoroutines();
// }
// else
// {
// bonus.interactable = false;
// showTimer.gameObject.SetActive(true);
// }
}
//else
// return false;
// PlayerPrefs.SetString("BONUS_END_TIME", "");
}
else
{
// return false;
}
}
Hours is only between 0-23, you likely want TotalHours or TotalDays.

How can I change a labels text on a certain time

The label must change when the page loads. I don't get any errors but the label stays what I named the label.
my code:
private void Form1_Load(object sender, EventArgs e)
{
DateTime curTime = DateTime.Now;
int one = 5; //times of day
int two = 12;
int three = 20;
string ogg = "Oggend";
string mid = "Middag";
string aan = "Aand";
if (curTime.Hour >= one && curTime.Hour <= two)
{
timelbl.Text = ogg;
}
else if (curTime.Hour > two && curTime.Hour < three)
{
timelbl.Text = mid;
}
else
{
timelbl.Text = aan;
}
}
I tried to put timelbl.Text = "Oggend" in aswell but it didn't work.
Oggend means Morning, Middag means Day and aand means Night
Using variables for "times of day" is redundant. You may keep them if that's what you want, but it won't be the best thing to do.
private void Form1_Load(object sender, EventArgs e) {
DateTime curTime = DateTime.Now;
int one = 5; //times of day
int two = 12;
int three = 8;
string ogg = "Oggend";
string mid = "Middag";
string aan = "Aand";
if (curTime.Hour >= one && curTime.Hour <= two)
{
timelbl.Text = ogg;
}
else if (curTime.Hour > two && curTime.Hour < three)
{
timelbl.Text = mid;
}
else
{
timelbl.Text = aan;
}
}
Your code seems to be fine. You just need to make sure that page load event fires so that the variable value assigned to the label. You should add a break point in page load event and ensure that the event fires properly.

Display selected rows in datagridview on notification popup

using c#, winforms, sqlite
datagridview has name, startdate, expirationdate columns
I have an application where the user clicks on a button, the click event will take the expirationdate in one of the columns and minus it from today's date which will then make the row light up if the number is < 61 (It must be less than). Basically it highlights rows where the date is close to today's date. Now I want a popup that shows the "name" columns of the rows that were highlighted but I'm not sure how to proceed. If I'm right I need to put it in the for loop and use an if case maybe?
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
string test = ds.Tables[0].Rows[i]["ExpirationDate"].ToString();
if(test != "")
{
DateTime expiraryDate = Convert.ToDateTime(test); //convert string to datetime
DateTime itoday = DateTime.Today; //get current date
DateTime today = Convert.ToDateTime(itoday); //convert string to datetime
// String daysdiffstring = (expiraryDate - today).TotalDays.ToString();
int daysdiffstring = expiraryDate.Subtract(today).Days;
string daysdifffstring = Convert.ToString(daysdiffstring);
int daysdiff = Convert.ToInt32(daysdiffstring);
if (daysdiff < 61 && daysdiff >= -1) //2 months close to expiry dangerous
{
dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Red;
dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Black;
}
}
PopupNotifier popup = new PopupNotifier();
popup.Image = Properties.Resources.information_icon;
popup.TitleText = "Notification on ending certificates";
popup.ContentText = "hello world"; //replace this
popup.Popup();
You need to add appropriate code in your for and if statement.
for (int i = 0; i<ds.Tables[0].Rows.Count; i++)
{
var nearToExpiryUsers = new List<string>();
----
Your code
----
if (daysdiff< 61 && daysdiff >= -1) //2 months close to expiry dangerous
{
dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Red;
dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Black;
nearToExpiryUsers.Add(ds.Tables[0].Rows[i]["name"]);
}
}
Then you need to iterate through each string in nearToExpiryUsers to create a formatted string(as per your choice) and then set this formatted string to popup.ContextText.
foreach (var expiredName in expiredNames)
{
popup.ContentText += expiredName + Environment.NewLine;
}

C# Windows Application Timer Stops

I have an Windows Application which uses timer like in the screen:
timer it's used to run a method every X minutes between 08:00:00 (Start Time) and 21:00:00 (Stop Time)
In the screen:
Next download Start at: shows what time the next run will occur
Time Left: shows the remaining time until next run will occur
Download Interval: time span between two runs
The method runs when the Next download Start = Current Time.
My issue is that event that the application is open and runs, the timer just stops after a while.
Any ideas why this happens, is this normal or am I doing something wrong in my code (i can post it if needed but now I was just asking to see if it's normal)?
Is there a way to prevent it or shell I create a checker and check his status regularly?
Thanks in advance for your support!
private System.Windows.Forms.Timer timerFrequency = new System.Windows.Forms.Timer();
public void LoadGeneraInfoPanel()
{
timerFrequency.Interval = 1000;
timerFrequency.Enabled = true;
this.timerFrequency.Tick += new System.EventHandler(this.timerFrequency_Tick);
timerFrequency.Start();
}
private void timerFrequency_Tick(object sender, EventArgs e)
{
txtGICurrTime.Text = DateTime.Now.ToString("HH:mm:ss");
if (drSystemParam["Auto"].ToString() == "True" && timerFrequency.Enabled)
{
if (txtGIFrequency.Text.ToString() != string.Empty && txtGIStopTime.Text.ToString() != string.Empty && txtGIStartTime.Text.ToString() != string.Empty)
{
int iHours = Convert.ToInt32(txtGIFrequency.Text.Substring(0, 2));
int iMinutes = Convert.ToInt32(txtGIFrequency.Text.Substring(3, 2));
int iSeconds = Convert.ToInt32(txtGIFrequency.Text.Substring(6, 2));
DateTime dCurrStartTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, Convert.ToInt32(txtGIStartTime.Text.Substring(0, 2)), Convert.ToInt32(txtGIStartTime.Text.Substring(3, 2)), Convert.ToInt32(txtGIStartTime.Text.Substring(6, 2)));
DateTime dCurrStopTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, Convert.ToInt32(txtGIStopTime.Text.Substring(0, 2)), Convert.ToInt32(txtGIStopTime.Text.Substring(3, 2)), Convert.ToInt32(txtGIStopTime.Text.Substring(6, 2)));
DateTime dCurrStartDownloadTime = dCurrStartTime;
for (int j = 0; dCurrStartDownloadTime < DateTime.Now & dCurrStartDownloadTime <= dCurrStopTime; j++)
dCurrStartDownloadTime = dCurrStartDownloadTime.AddHours(iHours).AddMinutes(iMinutes).AddSeconds(iSeconds);
var result = dCurrStartDownloadTime;
if (DateTime.Now > dCurrStartTime && DateTime.Now < dCurrStopTime.AddHours(-iHours).AddMinutes(-iMinutes).AddSeconds(-iSeconds))
{
if (txtNextDownloadTime.Text == String.Empty)
txtNextDownloadTime.Text = result.ToString("HH:mm:ss");
TimeSpan diff = result - DateTime.Now.AddSeconds(-1);
txtGITimeLeft.Text = string.Format("{0}:{1}:{2}", diff.Hours.ToString().PadLeft(2, '0'), diff.Minutes.ToString().PadLeft(2, '0'), diff.Seconds.ToString().PadLeft(2, '0'));
if (DateTime.Now.ToString("HH:mm:ss") == txtNextDownloadTime.Text)
{
timerFrequency.Stop();
txtNextDownloadTime.Text = result.ToString("HH:mm:ss");
Thread.Sleep(800);
timerFrequency.Enabled = true;
timerFrequency.Start();
btnEecuteMethod_Click(sender, e);
}
}
else
{
result = dCurrStartTime.AddDays(1);
txtNextDownloadTime.Text = result.ToString("HH:mm:ss");
TimeSpan diff = result - DateTime.Now.AddSeconds(-1);
txtGITimeLeft.Text = string.Format("{0}:{1}:{2}", diff.Hours.ToString().PadLeft(2, '0'), diff.Minutes.ToString().PadLeft(2, '0'), diff.Seconds.ToString().PadLeft(2, '0'));
}
}
else
{
timerFrequency.Enabled = false;
timerFrequency.Stop();
}
}
}

Invalid cast from double to datetime error

Hi I am getting invalid cast from double to datetime error when i run my ASP.NET MVC code.
This is my code :
Update: Hi I am adding my full code below. Please have a look into that.
Boolean locked = false;
if (frmcollection["lockStart"] != null && frmcollection["lockStart"] != "")
{
locked = Convert.ToBoolean(frmcollection["lockStart"].ToString());
}
else if (datelock == "")
{
locked = Convert.ToBoolean("0");
}
Boolean valid = true;
double inteval = 86400000 * Convert.ToDouble(frmcollection["autoFrequency"].ToString());
DateTime schedulestartDate = Convert.ToDateTime(frmcollection["autoStart"].ToString());
int startHour = Convert.ToInt32(frmcollection["autoStartHour"].ToString());
DateTime sd = schedulestartDate;
sd.AddHours(startHour);
DateTime filterStart = Convert.ToDateTime(frmcollection["periodStart"].ToString());
int filterStartHour = Convert.ToInt32(frmcollection["periodStartHour"].ToString());
DateTime fsd = filterStart;
fsd.AddHours(filterStartHour);
DateTime filterEnd = Convert.ToDateTime(frmcollection["periodEnd"].ToString());
int filterEndHour = Convert.ToInt32(frmcollection["periodEndHour"].ToString());
DateTime fed = filterEnd;
fed.AddHours(filterEndHour);
double sDate = sd.Second;
double sPeriod = sDate - fsd.Second;
double ePeriod = sDate - fed.Second;
if (sPeriod < ePeriod || sPeriod < 0 || ePeriod < 0)
{
valid = false;
}
if (valid)
{
for (int i = 0; i < 5; i++)
{
DateTime date = Convert.ToDateTime(sDate + (inteval * i));
if (locked)
{
DateTime psdate = Convert.ToDateTime(sDate - sPeriod);
}
else
{
DateTime psdate = Convert.ToDateTime(sDate + (inteval * i) - sPeriod);
}
DateTime pedate = Convert.ToDateTime(sDate + (inteval * i) - ePeriod);
}
}
else
{
}
When i debug I am gettin error in this line :
DateTime date = Convert.ToDateTime(sDate + (inteval * i));
Can someone help me in this??
You're adding a double to whatever interval * i resolves to.
You can't convert (cast) that to a DateTime, which is exactly what the error is telling you.
It seems as if you're looking for the date some (interval * i) seconds after the date "sd". If so, try:
for (int i = 0; i < 5; i++)
{
DateTime date = sd.AddSeconds(inteval * i);
if (locked)
{
DateTime psdate = sd.AddSeconds(-sPeriod);
}
else
{
DateTime psdate = sd.AddSeconds((inteval * i) - sPeriod));
}
DateTime pedate = sd.AddSeconds((inteval * i) - ePeriod);
}
//...
DateTime has a lot of methods to perform calculations on a specific date. For example DateTime.AddMillisecons which takes a double and returns a date.
MSDN DateTime.AddMilliseconds

Categories