I made a simple countdown timer but the timer goes into negative -1 : 59 : 59 when i input 0 : 0 : 0 on the textboxes. i tried to input 0 : 0 : 1 and the timer stopped at 0 : 0 : 0 and the messagebox appear on the screen
i have tried this code to prevent negative value but it stopped at -1 : 59 : 58
if (label1.Text == "-1")
{
timer1.Stop()
}
tried this code but it stopped at -1 : 59 : 59
if (h < 0)
{
timer1.Stop();
}
here is the codes
namespace Timer
{
public partial class Form1 : Form
{
int h;
int m;
int s;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
textBox1.Text = "0";
}
if (textBox2.Text == "")
{
textBox2.Text = "0";
}
if (textBox3.Text == "")
{
textBox3.Text = "0";
}
h = Convert.ToInt32(textBox1.Text);
m = Convert.ToInt32(textBox2.Text);
s = Convert.ToInt32(textBox3.Text);
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
s = s - 1;
if(s == -1)
{
m = m - 1;
s = 59;
}
if (m == -1)
{
h = h - 1;
m = 59;
}
if (h == 0 && m == 0 && s == 0)
{
timer1.Stop();
MessageBox.Show("Times up!", "Time");
}
string hh = Convert.ToString(h);
string mm = Convert.ToString(m);
string ss = Convert.ToString(s);
label1.Text = hh;
label2.Text = mm;
label3.Text = ss;
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Stop();
}
}
}
You code is doing exactly what you are telling it to do, the problem is that you are not dealing with the edge case of starting at 0:0:0.
I assume this would be considered an invalid input, so probably the easiest way to deal with this would be to check before you even start the timer in the button click:
h = Convert.ToInt32(textBox1.Text);
m = Convert.ToInt32(textBox2.Text);
s = Convert.ToInt32(textBox3.Text);
// one of these must be non-zero
if (h != 0 || m != 0 || s != 0)
{
timer1.Start();
}
else
{
// handle this how ever you want but you don't need to start a timer
// and really shouldn't start the timer
}
It would actually be a mistake to let the timer tick if the user entered all zeros because then they would get 1 second, when they asked for 0 seconds.
Even better would be to actually disable the button until a non-zero time has been entered. To do that I would suggest replacing the TextBox with NumericUpDown (because only numeric inputs are valid anyway) and then add handlers for their ValueChanged event. In that handler check in any of the three controls have a non-zero value and enable the button if they do. If they are all zero, disable the button.
An important aside here - the System.Windows.Forms.Timer is not particularly accurate so don't expect a timer set to tick every 1 second to actually tick every one second. It will be at least 1 second between each tick, but often it will be a few ms more. So your countdown will drift. If you set it to count down 1 minute (i.e. 60 seconds), don't be surprised if it actually takes 62 seconds to count down. If that's important to you, then you should record the current time when you start the timer and then check the difference between the current time and the time when you started the timer and use that to update your labels.
A better overall solution might look something like this:
DateTime end;
private void button1_Click(object sender, EventArgs e)
{
var h = hourNumericUpDown.Value;
var m = minuteNumericUpDown.Value;
var s = secondsNumericUpDown.Value;
if (h != 0 || m != 0 || s != 0)
{
var start = DateTime.Now;
var timeSpan = new TimeSpan(0,h,m,s);
end = start.Add(timeSpan);
countDownLabel.Text = timeSpan.ToString();
timer1.Start();
}
}
private void timer1_Tick(object sender, EventArgs e)
{
var timeleft = end - DateTime.Now;
if (timeLeft.Ticks < 0)
{
countDownLabel.Text = "00:00:00";
timer1.Stop();
MessageBox.Show("Times up!", "Time");
}
else
{
countDownLabel.Text = string.Format("{0:D2}:{1:D2}:{2:D2}",
timeLeft.Hours, timeLeft.Minutes, timeLeft.Seconds);
}
}
And then you'd probably be better off setting the timer to fire faster. Maybe every half second, or every quarter second so that the display is never off by more than about that much.
You're not covering the case in which 0:0:0 is provided.
Replace this:
s = s - 1;
if(s == -1)
{
m = m - 1;
s = 59;
}
if (m == -1)
{
h = h - 1;
m = 59;
}
with this:
if(s > 0 || m > 0 || h > 0)
{
s = s - 1;
if(s == -1)
{
m = m - 1;
s = 59;
}
if (m == -1)
{
h = h - 1;
m = 59;
}
}
You are not checking when h becomes negative, I have added one you can add yours.
if (s == -1)
{
m = m - 1;
s = 59;
}
if (m == -1)
{
h = h - 1;
m = 59;
}
/*I added such condition*/
if(h < 0)
{
h = 0;
m = 0;
s = 0;
}
if (h == 0 && m == 0 && s == 0)
{
timer1.Stop();
MessageBox.Show("Times up!", "Time");
return;//return early
}
Related
I'm trying to give the letters in my richtextbox different colors for my subnet calculator, but the richtextbox doesn't change the colors until the 26th letter.
How it looks:
int iValueSm = trackBarSmMask.Value;
rtbScroll.Text = "";
rtbScroll.SelectionStart = rtbScroll.TextLength;
rtbScroll.SelectionLength = 0;
for (int i = 1; i <= iValueSm; i++)
{
rtbScroll.SelectionColor = Color.Blue;
rtbScroll.AppendText("N");
if (i%8==0 && i != 32)
{
rtbScroll.Text = rtbScroll.Text + ".";
}
}
for (int i = iValueSm+1; i <= 32; i++)
{
rtbScroll.SelectionColor = Color.Red;
rtbScroll.AppendText("H");
if (i % 8 == 0 && i != 32)
{
rtbScroll.Text = rtbScroll.Text + ".";
}
}
labelAmountNetID.Text = "/" + iValueSm.ToString();
Well, can be a lot of approaches to deal with this problem but here is one suggestion:
// Track bar definitions...
private void SetTrackBarVals()
{
trackBar1.Minimum = 0;
trackBar1.Maximum = 31;
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
var counter = 0;
var dotsCounter = 0;
rtbScroll.Text = "";
int iValueSm = trackBar1.Value + 1; // +1 because we start counting from 0
for (int i = 1; i <= 32; i++)
{
if (counter > 0 && counter % 8 == 0)
{
// new octet
rtbScroll.AppendText(".");
dotsCounter++;
}
if (i > iValueSm)
{
// It is red
rtbScroll.AppendText("H");
rtbScroll.SelectionStart = (i - 1) + dotsCounter;
rtbScroll.SelectionLength = 1 ;
rtbScroll.SelectionColor = Color.Red;
}
else
{
rtbScroll.AppendText("N");
}
counter++;
}
}
Anytime you set the .Text() property, you RESET all formatting back to black and white.
Here is how I'd write it using SelectedText:
private void Form1_Load(object sender, EventArgs e)
{
updateRTB();
}
private void trackBarSmMask_ValueChanged(object sender, EventArgs e)
{
updateRTB();
}
private void trackBarSmMask_Scroll(object sender, EventArgs e)
{
updateRTB();
}
private void updateRTB()
{
rtbScroll.Text = "";
rtbScroll.SelectionStart = 0;
rtbScroll.SelectionLength = 0;
int iValueSm = trackBarSmMask.Value;
labelAmountNetID.Text = "/" + iValueSm.ToString();
for (int i = 1; i <= 32; i++)
{
rtbScroll.SelectionColor = (i <= iValueSm) ? Color.Blue : Color.Red;
rtbScroll.SelectedText = (i <= iValueSm) ? "N" : "H";
if (i % 8 == 0 && i != 32)
{
rtbScroll.SelectionColor = Color.Black;
rtbScroll.SelectedText = ".";
}
}
}
enter image description here
This is what I am aiming to do. In everytime the clock ticks, and i get some errors
Well this is my codes so far.
private void timer1_Tick(object sender, EventArgs e)
{
//get current time
int hh = DateTime.Now.Hour;
int mm = DateTime.Now.Minute;
int ss = DateTime.Now.Second;
int ms = DateTime.Now.Millisecond;
//time
string time = "";
//padding leading zero
if (hh < 10)
{ time += hh; }
else
{
if (hh >= 12)
{
int h = hh - 12;
if (h == 0)
{
time += 12;
}
else
{
time += h;
}
}
else { time += hh; }
}
time += ":";
if (mm < 10)
{ time += "0" + mm; }
else
{ time += mm; }
time += ":";
if (ss < 10)
{ time += "0" + ss; }
else
{ time += ss; }
//update Ltime label
string[] ports = SerialPort.GetPortNames();
// SerialPort.GetPortNames() returns multiple strings in an array, not just one string.
//You need to go through each item in the array, and run your Contains() and Add() for each item.
foreach (var p in ports) // Go through each string in the array
{
if (!comboBox1.Items.Contains(p))
comboBox1.Items.Add(p);
}
if (hh < 12)
{ Ltime.Text = time + "am"; }
else { Ltime.Text = time + "pm"; }
int count = sched1.Lines.Count();//isulod sa var count kung pila ka line unod ni sched1.Text
if (count == i)
{
display2.Text = "No Available Schedule";
}
else
{
/////reading the schedules
for (int x = 0; x < count; x++)
{
if (string.IsNullOrWhiteSpace(sched1.Lines[x+1]))
{
display2.Text = "Empty";
}
/////okay ni/
else
{
if (sched1.Lines[x+1] == (DateTime.Now.DayOfWeek.ToString()))
{
if (string.IsNullOrWhiteSpace(sched2.Text))
{
display2.Text = "Empty";
}
///okay mn
else
{
int count2 = sched2.Lines.Count();
if (count2 == i)
{
display2.Text = "No Available Schedule";
}
else
{
for (int y = 0; x < count2; y++)
if (sched2.Lines[y+1].Equals(Ltime.Text))
{
serialPort1.Write("1");
try
{
display2.Text = serialPort1.ReadExisting();
}
catch (TimeoutException)
{
display2.Text = "Timeout Exception";
}
}
}
}
}
else { display2.Text = "Empty"; }
//ok mn
}
}
}
}
But it display "Index was outside the bounds of the array." in
if (string.IsNullOrWhiteSpace(sched1.Lines[x+1])) I don't know what would be the problem.
This question already has an answer here:
Why do I only see some of my text output when my Window Forms application has a loop?
(1 answer)
Closed 7 years ago.
I am trying to combine prime numbers, even numbers and odd numbers and their results in a Windows Form Application. I have tested the code in Console but in Windows Form it will not loop to the next applicable number. For example: In console 1 - 10 in primes would result in "2, 3, 5, 7", however in Windows Form Application it will result in "2"
public partial class NumberCalc : Form
{
public NumberCalc()
{
InitializeComponent();
}
private void Primes_CheckedChanged(object sender, EventArgs e)
{
{
int f = Convert.ToInt32(Min.Text);
int i = Convert.ToInt32(Max.Text);
bool isPrime = true;
for (f = 0; f <= i; f++)
{
for (int j = 2; j <= i; j++)
{
if (f != j && f % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
string final;
final = ("The Prime Numbers Are:" + f);
Result.Text = final;
}
isPrime = true;
}
}
}
private void Result_TextChanged(object sender, EventArgs e)
{
}
private void Min_TextChanged(object sender, EventArgs e)
{
}
private void Evens_CheckedChanged(object sender, EventArgs e)
{
int f = Convert.ToInt32(Min.Text);
int i = Convert.ToInt32(Max.Text);
for (f = 0; f >= i; f++)
{
if (f % 2 == 0)
{
{
string final;
final = ("The Even Numbers Are:" + f);
Result.Text = final;
}
}
}
}
private void Odds_CheckedChanged(object sender, EventArgs e)
{
int f = Convert.ToInt32(Min.Text);
int i = Convert.ToInt32(Max.Text);
for (f = 0; f <= i; f++)
{
if (f % 2 != 0)
{
{
string final;
final = ("The Even Numbers Are:" + f);
Result.Text = final;
}
}
}
}
}
}
Change your code to:
private void Primes_CheckedChanged(object sender, EventArgs e)
{
{
string final = "The Prime Numbers Are:";// you need to keep the result out of the loop instead of reset it everytime
int f = Convert.ToInt32(Min.Text);
int i = Convert.ToInt32(Max.Text);
bool isPrime = true;
for (f = 0; f <= i; f++)// why set f=0 here ? Does not f = min already ?
{
for (int j = 2; j <= i; j++)// maybe j < f not j <= i
{
if (f != j && f % j == 0)// then remove f != j here
{
isPrime = false;
break;
}
}
if (isPrime)
final = final + " " + f;// then add your found number to the result here
isPrime = true;
}
Result.Text = final;
}
}
Even and Odd goes the same.BTW 1 is not prime number, am I right ?
I would combine your loops/checks into one method like this:
private void Form1_Load(object sender, EventArgs e)
{
this.Primes.CheckedChanged += Options_CheckedChanged;
this.Evens.CheckedChanged += Options_CheckedChanged;
this.Odds.CheckedChanged += Options_CheckedChanged;
this.Min.TextChanged += Range_Changed;
this.Max.TextChanged += Range_Changed;
CheckNumbers();
}
private void Range_Changed(object sender, EventArgs e)
{
CheckNumbers();
}
private void Options_CheckedChanged(object sender, EventArgs e)
{
CheckNumbers();
}
private void CheckNumbers()
{
int min, max;
try
{
min = Convert.ToInt32(Min.Text);
max = Convert.ToInt32(Max.Text);
}
catch (Exception)
{
Results.Text = "Invalid Range!";
return;
}
List<int> lstPrimes = new List<int>();
List<int> lstEvens = new List<int>();
List<int> lstOdds = new List<int>();
if (Primes.Checked || Evens.Checked || Odds.Checked)
{
bool isPrime;
for (int f = min; f <= max; f++)
{
if (Primes.Checked)
{
isPrime = true;
for (int j = 2; j <= max; j++)
{
if (f != j && f % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
lstPrimes.Add(f);
}
}
int modResult = f % 2;
if (Evens.Checked && modResult == 0)
{
lstEvens.Add(f);
}
if (Odds.Checked && modResult != 0)
{
lstOdds.Add(f);
}
}
}
StringBuilder sb = new StringBuilder();
if (Primes.Checked)
{
sb.AppendLine("The Prime Numbers Are:" + String.Join(",", lstPrimes));
}
if (Evens.Checked)
{
sb.AppendLine("The Even Numbers Are:" + String.Join(",", lstEvens));
}
if (Odds.Checked)
{
sb.AppendLine("The Odd Numbers Are:" + String.Join(",", lstOdds));
}
Results.Text = sb.ToString();
}
I think LINQ is more suitable here, You can try this:
int[] numbers = Enumerable.Range(f, i-f).ToArray<int>();
string oddNumbers=string.Join(",", from number in numbers
where (number % 2)!=0
select number);
string evenNumbers = string.Join(",", from number in numbers
where (number % 2) == 0
select number);
Result.Text = "The Even Numbers Are:" + evenNumbers;
Result.Text = "The Odd Numbers Are:" + oddNumbers;
Updates for Prime number:
var primeNumbers= string.Join(",",from number in numbers
where (IsPrime(number))
select number);
Where IsPrime() method is defined as follows?
private static bool IsPrime(int number)
{
for (int i = 2; i < number; i ++)
if (number % i == 0) return false;
return true;
}
I am currently developing a program that is using tab same like Google Chrome Tabs,
The tab is working fine, no problem.
But I come into a condition that I can drag the tab even out of monitor screen (left and right edge).
The Question is, how can I restrict the tab dragged into the edge of the screen??
So the tab will not go pass through the screen. Basically it is only about aesthetic purpose..
Be reminded that I have made research from the google and this website but still can't figure it out how to do it..
Here is a piece of the codes.
private bool draggingWindow;
private Size finalSize;
private double overlap;
private double leftMargin;
private double rightMargin;
private double maxTabWidth;
private double minTabWidth;
private double defaultMeasureHeight;
private double currentTabWidth;
private int captureGuard;
private int originalIndex;
private int slideIndex;
private List<double> slideIntervals;
private ChromeTabItem draggedTab;
private Point downPoint;
private ChromeTabControl parent;
public Rect addButtonRect;
private Size addButtonSize;
public Button addButton;
private bool modifyLeftOffset, modifyTopOffset;
private Point origCursorLocation;
private double origHorizOffset, origVertOffset;
protected override void OnPreviewMouseMove(MouseEventArgs e)
{
try
{
base.OnPreviewMouseMove(e);
if (this.addButtonRect.Contains(e.GetPosition(this)) && this.addButton.Background != Brushes.White && this.addButton.Background != Brushes.DarkGray)
{
this.addButton.Background = Brushes.White;
this.InvalidateVisual();
}
else if (!this.addButtonRect.Contains(e.GetPosition(this)) && this.addButton.Background != null)
{
this.addButton.Background = null;
this.InvalidateVisual();
}
if (this.draggedTab == null || this.draggingWindow) { return; }
Point nowPoint = e.GetPosition(this);
this.addButton.Visibility = Visibility.Hidden;
double newHorizontalOffset;
if (this.modifyLeftOffset)
newHorizontalOffset = this.origHorizOffset + (nowPoint.X - this.origCursorLocation.X);
else
newHorizontalOffset = this.origHorizOffset - (nowPoint.X - this.origCursorLocation.X);
Thickness margin = new Thickness(nowPoint.X - this.downPoint.X, 0, this.downPoint.X - nowPoint.X, 0);
this.draggedTab.Margin = margin;
Rect elemRect = this.CalculateDragElementRect(newHorizontalOffset, 1);
bool leftAlign = elemRect.Left < 0;
bool rightAlign = elemRect.Right > this.ActualWidth;
if (leftAlign)
newHorizontalOffset = modifyLeftOffset ? 0 : this.ActualWidth - elemRect.Width;
else if (rightAlign)
newHorizontalOffset = modifyLeftOffset ? this.ActualWidth - elemRect.Width : 0;
if (this.modifyLeftOffset)
Canvas.SetLeft(this.draggedTab, newHorizontalOffset);
else
Canvas.SetRight(this.draggedTab, newHorizontalOffset);
base.OnPreviewMouseMove( e );
if (margin.Left != 0)
{
int guardValue = Interlocked.Increment(ref this.captureGuard);
if (guardValue == 1)
{
this.originalIndex = this.draggedTab.Index;
this.slideIndex = this.originalIndex + 1;
this.slideIntervals = new List<double>();
this.slideIntervals.Add(double.NegativeInfinity);
for (int i = 1; i <= this.Children.Count; i += 1)
{
var diff = i - this.slideIndex;
var sign = diff == 0 ? 0 : diff / Math.Abs(diff);
var bound = Math.Min(1, Math.Abs(diff)) * ((sign * this.currentTabWidth / 3) + ((Math.Abs(diff) < 2) ? 0 : (diff - sign) * (this.currentTabWidth - this.overlap)));
this.slideIntervals.Add(bound);
}
this.slideIntervals.Add(double.PositiveInfinity);
this.CaptureMouse();
}
else
{
int changed = 0;
if (this.slideIntervals != null)
{
if (margin.Left < this.slideIntervals[this.slideIndex - 1])
{
SwapSlideInterval(this.slideIndex - 1);
this.slideIndex -= 1;
changed = 1;
}
else if (margin.Left > this.slideIntervals[this.slideIndex + 1])
{
SwapSlideInterval(this.slideIndex + 1);
this.slideIndex += 1;
changed = -1;
}
}
if (changed != 0)
{
var rightedOriginalIndex = this.originalIndex + 1;
var diff = 1;
if (changed > 0 && this.slideIndex >= rightedOriginalIndex)
{
changed = 0;
diff = 0;
}
else if (changed < 0 && this.slideIndex <= rightedOriginalIndex)
{
changed = 0;
diff = 2;
}
ChromeTabItem shiftedTab = this.Children[this.slideIndex - diff] as ChromeTabItem;
if (shiftedTab != this.draggedTab)
{
StickyReanimate(shiftedTab, changed * (this.currentTabWidth - this.overlap), .13);
}
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
Any response and attention is really appreciated..
Thank you
I have 4 checkboxes.while,checking 1 at a time,I m getting its corresponding datagrid view.I want to get the total from each of the datagrid view and store it in a textbox.
Then i want to display the sum from all the datagrid view.Now i am getting only value from one datagrid view.how can i do this?
private void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
{
if (checkBox1.Checked == true)
{
if (e.ColumnIndex == 2 || e.ColumnIndex == 3)
{
int a = Convert.ToInt32(dataGridView1.CurrentRow.Cells[2].Value);
int b = Convert.ToInt32(dataGridView1.CurrentRow.Cells[3].Value);
dataGridView1.CurrentRow.Cells[4].Value = a * b;
// sum = 0;
for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[4].Value);
}
// textBox2.Text = sum.ToString();
}
}
else if(checkBox2.Checked==true)
{
if (e.ColumnIndex == 2 || e.ColumnIndex == 3)
{
int a = Convert.ToInt32(dataGridView1.CurrentRow.Cells[2].Value);
int b = Convert.ToInt32(dataGridView1.CurrentRow.Cells[3].Value);
dataGridView1.CurrentRow.Cells[4].Value = a * b;
// s = 0;
for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
s += Convert.ToInt32(dataGridView1.Rows[i].Cells[4].Value);
}
}
}
else if (checkBox3.Checked == true)
{
if (e.ColumnIndex == 2 || e.ColumnIndex == 3)
{
int a = Convert.ToInt32(dataGridView1.CurrentRow.Cells[2].Value);
int b = Convert.ToInt32(dataGridView1.CurrentRow.Cells[3].Value);
dataGridView1.CurrentRow.Cells[4].Value = a * b;
// u = 0;
for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
u += Convert.ToInt32(dataGridView1.Rows[i].Cells[4].Value);
}
}
}
else if(checkBox4.Checked==true)
{
if (e.ColumnIndex == 2 || e.ColumnIndex == 3)
{
int a = Convert.ToInt32(dataGridView1.CurrentRow.Cells[2].Value);
int b = Convert.ToInt32(dataGridView1.CurrentRow.Cells[3].Value);
dataGridView1.CurrentRow.Cells[4].Value = a * b;
// m = 0;
for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
m += Convert.ToInt32(dataGridView1.Rows[i].Cells[4].Value);
}
}
}
You're only executing the first block of code where the if-expression evaluates to true.
Remove the else in the other blocks so that the expression can be evaluated too.
An else-block is only executed when the if-block evaluates to false.
If (checkBox1.Checked)
{
// Your stuff
}
If (checkBox2.Checked)
{
// Your stuff
}
If (checkBox3.Checked)
{
// Your stuff
}
If (checkBox3.Checked)
{
// Your stuff
}
Note that you can write the check a bit shorter. You can ommit the = true part.
EDIT
When doing the above, you will indeed execute Your stuffeverytime your checkbox is unchecked and checked again.
There are 2 possibilities to accompllish the desired behaviour:
Option 1: Remove the columns when the box is unchecked:
If (checkBox1.Checked)
{
// Add columns
}
else
{
// Remove columns
}
If (checkBox2.Checked)
{
// Add columns
}
else
{
// Remove columns
}
Option 2: Check whether the columns exist or not. This will keep the columns in place, even when the checkbox is unchecked, but will not add new ones, if they already exist.
If (checkBox1.Checked) && ( columns are not present)
{
// Add columns
}
If (checkBox2.Checked) && ( columns are not present)
{
// Add comlumns
}
In both cases you'll get a maximum of 2 other columns.