Counter doesn't start on time - c#

Ok, I'm trying to explain this on a simple example.
I want counter to have the value 0 at the beginning. label1 is invisible until I click on button1. My problem now is that when I click on button1 for the first time, 0 appears instead of 1. Meaning I need to click two times on button1, so that "1" appears. (I'm quite new to C#, so don't use jargon please =P)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
label1.Visible = false;
}
int counter = 0;
private void button1_Click(object sender, EventArgs e)
{
label1.Visible = true;
label1.Text = "number " + counter;
counter++;
}
}

Look closely at your click method:
private void button1_Click(object sender, EventArgs e)
{
label1.Visible = true;
label1.Text = "number " + counter;
counter++;
}
You are first assigning the (current) value of counter to label1.Text and then increment it. Swap statements 2 and 3:
private void button1_Click(object sender, EventArgs e)
{
label1.Visible = true;
counter++;
label1.Text = "number " + counter;
}

Either:
Initialize counter to 1
Increment the counter before showing it
label1.Text = "number " + (++counter).ToString();
or
counter++;
label1.Text = "number " + counter.ToString();
Use (counter+1) as your value
label1.Text = "number " + (counter+1).ToString();

Related

Why is the text not showing up on screen?

I'm trying to create a countdown where the text displays, "GAME STARTS IN: " and using a for loop and Thread.Sleep a variable counts down from three. I started by using the designer to create the "game starts in:" part, but after the variable wouldn't show up I moved it to code. Now nothing shows up. This is what I have now in my timer method:
if (!countedDown)
DoCountdown();
Countdown.Hide();
And then in a DoCountdown method:
this.Countdown.BackColor = System.Drawing.Color.Transparent;
this.Countdown.ForeColor = System.Drawing.Color.White;
this.Countdown.Location = new System.Drawing.Point(360, 17);
this.Countdown.Name = "Countdown";
this.Countdown.Font = new System.Drawing.Font("Segoe UI", 12F,
System.Drawing.FontStyle.Regular,
System.Drawing.GraphicsUnit.Point);
this.Countdown.Size = new System.Drawing.Size(185, 24);
this.Countdown.TabIndex = 6;
countedDown = true;
for (int i = 3; i > 0; i--)
{
Countdown.Text = "GAME STARTS IN: " + i;
System.Threading.Thread.Sleep(1000);
}
I put a breakpoint at System.Threading.Thread.Sleep(100) and everything seemed normal. Countdown.Text was equal to "GAME STARTS IN: 3". After trying to integrate the solutions the text doesn't show up. Here is some more context in my code:
This is from my start screen form
private void QuitGame(object sender, EventArgs e)
{
Application.Exit();
}
private void StartMultiplayerGame(object sender, EventArgs e)
{
GameScreen startGame = new GameScreen();
startGame.Show();
Hide();
}
Try something like below. A button is used to start the timer and set the initial values.
int count = 3;
private void button2_Click(object sender, EventArgs e) {
timer1.Interval = 1000;
count = 3;
label1.Text = "GAME STARTS IN: " + count;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e) {
count--;
if (count != 0) {
label1.Text = "GAME STARTS IN: " + count;
}
else {
timer1.Stop();
label1.Text = "GAME STARTED";
MessageBox.Show(" -> GO");
}
}
Edit per OP comments.
Try the code like this in the start screen form...
private void StartMultiplayerGame(object sender, EventArgs e) {
count = 3;
label1.Text = "GAME STARTS IN: " + count;
timer1.Start();
}
Then change the timer code to...
private void timer1_Tick(object sender, EventArgs e) {
count--;
if (count != 0) {
label1.Text = "GAME STARTS IN: " + count;;
}
else {
timer1.Stop();
label1.Text = "Game Started";
GameScreen startGame = new GameScreen();
startGame.Show();
this.Hide();
}
}
loop blocking the main thread to refresh UI so the required scenario can be archived by moving the loop to a separate method
void doCountDown()
{
for (int i = 10; i > 0; i--)
{
setCountDownText( "GAME STARTS IN: " + i);
System.Threading.Thread.Sleep(1000);
}
}
creating anew thread that start this method
new System.Threading.Thread(new System.Threading.ThreadStart(doCountDown)).Start();
and because of the need to update UI in another thread and to make it safe separate the setText in a separate method that update based on checking required to invoke property this will make it work in all cases
void setCountDownText(string txtValue)
{
if (Countdown.InvokeRequired)
{
Action safeWrite = delegate { setCountDownText(txtValue); };
Countdown.Invoke(safeWrite);
}
else
Countdown.Text = txtValue;
}
The "modern" way to do this is using async/await.
For example, launching the DoCountdown() from a button handler could look like this:
async void testBtn_Click(object sender, EventArgs e)
{
await DoCountdown();
}
async Task DoCountdown()
{
// <Initialisation of Countdown elided for brevity>
for (int i = 3; i > 0; i--)
{
Countdown.Text = "GAME STARTS IN: " + i;
await Task.Delay(1000);
}
}
However, whatever calls DoCountdown() will need to be declared as async, and so on up the call tree.
Note that the only acceptable place to have async void rather than async Task as a return type for an async method is where the method is an event handler such as the button handler in the example above.

How to make label text(number) change by clicking checkbox?

Teacher gave us an assignment. Checkboxes are lessons that students may choose and labels under them are the free spots left. Basically everytime a lesson(checkbox) selected the number connected to it at label should lessen minus 1. if person unchecks it, number should return to basic.
Sorry for my English, i hope it's understandable.
You can try to subscribe to the CheckedChanged event for each checkbox. And use Convert.ToInt32 Method to get the value in labels. Then judge the checkbox selected via swicth statement.
public Form1()
{
InitializeComponent();
checkBox1.CheckedChanged += checkBox_CheckedChanged;
checkBox2.CheckedChanged += checkBox_CheckedChanged;
checkBox3.CheckedChanged += checkBox_CheckedChanged;
}
private void checkBox_CheckedChanged(object sender, EventArgs e)
{
if (((CheckBox)sender).Checked)
{
switch (((CheckBox)sender).Name)
{
case "checkBox1":
labelofcb1.Text = (Convert.ToInt32(labelofcb1.Text) + 1).ToString();
break;
case "checkBox2":
labelofcb2.Text = (Convert.ToInt32(labelofcb2.Text) + 1).ToString();
break;
case "checkBox3":
labelofcb3.Text = (Convert.ToInt32(labelofcb3.Text) + 1).ToString();
break;
}
}
else
{
switch (((CheckBox)sender).Name)
{
case "checkBox1":
labelofcb1.Text = (Convert.ToInt32(labelofcb1.Text) - 1).ToString();
break;
case "checkBox2":
labelofcb2.Text = (Convert.ToInt32(labelofcb2.Text) - 1).ToString();
break;
case "checkBox3":
labelofcb3.Text = (Convert.ToInt32(labelofcb3.Text) - 1).ToString();
break;
}
}
}
That's an example where I picked the checkedchanged property of each of the checkboxs and this is the function in each of them. you can change the initial value or the changed value as you want by changing the 0 or the ++ or the --. You just add the two if conditions from each function to your function and change the name in them to reflect the name of your label.
public partial class Form1 : Form
{
int counter=0;
public Form1()
{
InitializeComponent();
label1.Text = counter.ToString();
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
counter++;
label1.Text = counter.ToString();
}
if (!checkBox1.Checked)
{
counter--;
label1.Text = counter.ToString();
}
}
private void checkBox3_CheckedChanged(object sender, EventArgs e)
{
if (checkBox3.Checked)
{
counter++;
label1.Text = counter.ToString();
}
if (!checkBox3.Checked)
{
counter--;
label1.Text = counter.ToString();
}
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
if (checkBox2.Checked)
{
counter++;
label1.Text = counter.ToString();
}
if (!checkBox2.Checked)
{
counter--;
label1.Text = counter.ToString();
}
}
}

I am writing a c# windows form code

I am writing a c# windows form code to
get the number from button1 and button2 and add them together in a text box but The compiler argues on the convert.toint32(textbox3.text) statement
and also it increases the value of the two variable and three variable how can I keep it constant but increase the value of textbox
and I need a solution?
int Three = 0;
int Two = 0;
//int one = 0;
int sum = 0;
// int sum = 0;
//int dec = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// MessageBox.Show("Enter the teams` name");
}
private void button1_Click(object sender, EventArgs e)
{
//Three += 3;
//textBox3.Text = sum.ToString();
Three += 3;
sum = Convert.ToInt32(textBox3.Text) + Three;
textBox3.Text = sum.ToString();
}
private void button2_Click(object sender, EventArgs e)
{
Two += 2;
sum = Two + Convert.ToInt32(textBox3.Text) + Three;
textBox3.Text =Convert.ToInt32(textBox3.Text) + Two.ToString();
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
textBox3.Text = 0.ToString();
}
`
Change
sum = Convert.ToInt32(textBox3.Text) + Three;
To
sum = Convert.ToInt32(textBox3.Text == "" ? "0" : textBox3.Text) + 3;
Also, remove
private void textBox3_TextChanged(object sender, EventArgs e)
{
textBox3.Text = 0.ToString(); // this
}
because it doesn't make any sense.
Your variables belong to class and they are accessible for initialization in constructor. This can be done in many ways but you need to check if textboxes have values then try to convert it and add it.
private int Two;
private int Three;
private int sum;
public Form1()
{
this.Two = 0;
this.Three = 0;
this.sum = 0;
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// MessageBox.Show("Enter the teams` name");
}
private void button1_Click(object sender, EventArgs e)
{
this.Three += 3;
sum = textBox3.Text != String.Empty ? Convert.ToInt32(textBox3.Text) : 0;
textBox3.Text = Convert.ToString(sum + this.Three);
}
... same for number Two
private void textBox3_TextChanged(object sender, EventArgs e)
{
textBox3.Text = "0";
}

Maximum value in the track bar

I have a button that adds +100 to the track Bar.
Maximum value 43000, if the value is at 43000 and clicking the button will give error.
Value '43001' is not valid for 'Value'. 'Value' must be between 'Minimum' and 'Maximum'.
private void button41_Click(object sender, EventArgs e)
{
trackBar1.Value = trackBar1.Value += 100;
label27.Text = "" + trackBar1.Value;
}
Issue resolved:
public Form1()
{
me = this;
InitializeComponent();
trackBar1.Maximum = 43000;
trackBar1.Minimum = 40;
}
button
private void button41_Click(object sender, EventArgs e)
{
if (trackBar1.Value + 100 <= trackBar1.Maximum)
{
trackBar1.Value = trackBar1.Value += 100;
label27.Text = "Frequency = " + trackBar1.Value;
}
else
{
MessageBox.Show("Max value = " + trackBar1.Maximum);
}
}
42990 + 100 without errors if I click add
Message displayed when trying add more than the supported value
The message already says all: The value may not be greater than the max-value.
Just add a condition before you increment the value:
if (trackBar1.Value < trackBar1.Maximum)
trackBar1.Value++;
Or here your complete event handler:
private void button41_Click(object sender, EventArgs e)
{
if (trackBar1.Value < trackBar1.Maximum)
{
trackBar1.Value++;
label27.Text = trackBar1.Value;
}
else
{
MessageBox.Show("Max value = " + trackBar1.Maximum);
}
}

why does the CLEAR button seem to disable my listbox label output?

When I run my program with a listbox everything works after selecting the items and pressing enter, but when I press the clear button and I select the items again and press enter nothing happens. I've tried the following for the clear button and they clear my label text and the selected listbox but I can no longer produce another output when I try pressing enter button again after selecting the items.
public partial class frmLabSix : Form
{
public string strCakes;
public int cakeCost;
public frmLabSix()
{
InitializeComponent();
}
private void lstCakes_SelectedIndexChanged(object sender, EventArgs e)
{
for (int index = 0; index < lstCakes.SelectedItems.Count; index++)
{
strCakes += Environment.NewLine + lstCakes.SelectedItems[index].ToString();
if (lstCakes.SelectedIndices[index] == 0) cakeCost += 18;
if (lstCakes.SelectedIndices[index] == 1) cakeCost += 25;
if (lstCakes.SelectedIndices[index] == 2) cakeCost += 40;
if (lstCakes.SelectedIndices[index] == 3) cakeCost += 30;
}
}
private void lblOrdered_Click(object sender, EventArgs e)
{
}
private void btnEnter_Click(object sender, EventArgs e)
{
double tax = 1.13;
lblOrdered.Text = "You have ordered: " + strCakes + '\n' + "Total Cost: " + (tax * cakeCost).ToString("C");
lblOrdered.Visible = true;
}
private void btnClear_Click(object sender, EventArgs e)
{
lstCakes.SelectedItems.Clear();
lblOrdered.Visible = false;
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
}
Can someone tell me why this is?
This line of code hides your label.
lblOrdered.Visible = false;
You make your label invisible on clear button click. Do you reset its visibility after?
I don't know, what happens in other part of your code, but it should probably be like this:
// if the label is not visible, the next line won't make it visible implicitly
lblOrdered.Text = ...
//you should set label's visibility explicitly
if (!lblOrdered.Visible)
lblOrdered.Visible = true;
Setting label's text doesn't make it visible. If you hide it with your own code, you should make label visible explicitly as well.

Categories

Resources