I have the following code:
protected void Button1_Click(object sender, EventArgs e)
{
count1++;
}
I want the counter count1 to increase every time someone clicks on the button. However, so far it only counts the first click, and not any other following, so it's always stuck on 1. Outside, I have declared it and set its initial value to 0. Where is the problem? (I use visual studio 2015)
Edit: This is the whole code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Statistics : System.Web.UI.Page
{
int count1 = 0, count2 = 0;
string minima = "Καλησπέρα";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
TextBox1.Text = minima;
Label1.Text = "Αυτή την στιγμή χρησιμοποιούν τον ιστότοπο " + Convert.ToString(Application["UserCount"]) + " χρήστες";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox2.Text = TextBox1.Text;
count1++;
Label2.Text = "Κλικ από προηγούμενους χρήστες: " + Convert.ToString(count1);
Label3.Text = "Τρέχοντα κλικ: " + Convert.ToString(count1 + count2);
}
}
(yes I know count2 is not changing its value at any point, the code is still in progress regarding that, as it is there for another reason so let's ignore it for now)
Your counters are reseting every postback
try this
static int count1,count2;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
TextBox1.Text = minima;
Label1.Text = "Αυτή την στιγμή χρησιμοποιούν τον ιστότοπο " + Convert.ToString(Application["UserCount"]) + " χρήστες";
count1 = 0;
count2 = 0;
}
}
Related
I have been tasked to create a calculator on a C# web application, however I noticed that when I use variables set in other buttons, the programs sets them to 0, specifically the 'num' and 'sign' variable which I assigned in the PlusBut but when actually using them in the EqualBut they are assigned to 0. My code works in a windows form but this is my first time using website application.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1 {
public partial class About: System.Web.UI.Page {
int sign;
double num, num2;
protected void Page_Load(object sender, EventArgs e) { }
protected void Button4_Click(object sender, EventArgs e) { }
protected void But0_Click(object sender, EventArgs e) {
AnswerBox.Text = AnswerBox.Text + "0";
}
protected void But1_Click(object sender, EventArgs e) {
AnswerBox.Text = AnswerBox.Text + "1";
}
protected void But2_Click(object sender, EventArgs e) {
AnswerBox.Text = AnswerBox.Text + "2";
}
protected void But3_Click(object sender, EventArgs e) {
AnswerBox.Text = AnswerBox.Text + "3";
}
protected void But4_Click(object sender, EventArgs e) {
AnswerBox.Text = AnswerBox.Text + "4";
}
protected void But5_Click(object sender, EventArgs e) {
AnswerBox.Text = AnswerBox.Text + "5";
}
protected void But6_Click(object sender, EventArgs e) {
AnswerBox.Text = AnswerBox.Text + "6";
}
protected void But7_Click(object sender, EventArgs e) {
AnswerBox.Text = AnswerBox.Text + "7";
}
protected void But8_Click(object sender, EventArgs e) {
AnswerBox.Text = AnswerBox.Text + "8";
}
protected void But9_Click(object sender, EventArgs e) {
AnswerBox.Text = AnswerBox.Text + "9";
}
protected void PlusBut_Click(object sender, EventArgs e) {
num = double.Parse(AnswerBox.Text);
AnswerBox.Text = "";
sign = 1;
}
protected void DecBut_Click(object sender, EventArgs e) {
AnswerBox.Text = AnswerBox.Text + ".";
}
protected void MinusBut_Click(object sender, EventArgs e) {
num = double.Parse(AnswerBox.Text);
AnswerBox.Text = "";
sign = 2;
}
protected void MultBut_Click(object sender, EventArgs e) {
num = double.Parse(AnswerBox.Text);
AnswerBox.Text = "";
sign = 3;
}
protected void DivButton_Click(object sender, EventArgs e) {
num = double.Parse(AnswerBox.Text);
AnswerBox.Text = "";
sign = 4;
}
protected void EqualBut_Click(object sender, EventArgs e) {
num2 = double.Parse(AnswerBox.Text);
AnswerBox.Text = "" + num + " " + num2 + " " + sign;
}
}
}
Essentially when you trigger a postback (by clicking a button in your case), a new instance of the About class is created and the previous values of your fields are lost.
You should read about ASP Page Life Cycle Events.
There are multiple approaches to making variables persistent, one is to use Session or ViewState variables, which is probably the simplest solution in your case and should be sufficient for a calculator.
double num1
{
get { return Convert.ToDouble(ViewState["num1"] ?? 0); }
set { ViewState["num1"] = value; }
}
Another approach would be to use JavaScript to avoid postbacks, however that would increase the complexity of your app by combining client side and server side actions.
I'm guessing a bit, but I think your problem is that web applications don't persist from one button press to another. Every time the user presses a button, the browser sends a request to the server. The server creates the web application and gives it the request, and the application produces the result.
You need to persist values from one request to the next. There are several ways to do this, but it's normal to save them to a session. The exact implantation depends on what web technology you're using.
ASP.NET is server side. So each time a click is triggered at client side a new instance of About is created and sign, num and num2 are created with default value (aka 0).
Either change to a client side programming language as JavaScript or define the values as static. Static variables are linked to the class and not an instance of it, so they will hold the value between callbacks:
public partial class About : System.Web.UI.Page
{
static int sign;
static double num;
static double num2;
/* ... */
protected void PlusBut_Click(object sender, EventArgs e)
{
About.num = double.Parse(AnswerBox.Text);
AnswerBox.Text = "";
sign = 1;
}
}
We just started using c# and the whole class knows nothing.
Yet, the teacher told us to use WinForms and c# to make a program that used bubblesort.
I looked around the web and only found validation for the text boxes (numbers only).
I'm new here but I would like to ask for help if possible.
We have to deliver this work today and we've got nothing so far.
This is the code I have.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace maedofeixeira
{
public partial class Form1 : Form
{
int[] elementos = new int[5];
public Form1()
{
InitializeComponent();
}
private void TextBox1_TextChanged(object sender, EventArgs e)
{
if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "[^0-9]"))
{
MessageBox.Show("SO NUMEROS!!!CRL.");
textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1);
}
}
private void TextBox2_TextChanged(object sender, EventArgs e)
{
if (System.Text.RegularExpressions.Regex.IsMatch(textBox2.Text, "[^0-9]"))
{
MessageBox.Show("SO NUMEROS!!!CRL.");
textBox2.Text = textBox2.Text.Remove(textBox2.Text.Length - 1);
}
}
private void TextBox3_TextChanged(object sender, EventArgs e)
{
if (System.Text.RegularExpressions.Regex.IsMatch(textBox3.Text, "[^0-9]"))
{
MessageBox.Show("SO NUMEROS!!!CRL.");
textBox3.Text = textBox3.Text.Remove(textBox3.Text.Length - 1);
}
}
private void TextBox4_TextChanged(object sender, EventArgs e)
{
if (System.Text.RegularExpressions.Regex.IsMatch(textBox4.Text, "[^0-9]"))
{
MessageBox.Show("SO NUMEROS!!!CRL.");
textBox4.Text = textBox4.Text.Remove(textBox4.Text.Length - 1);
}
}
private void TextBox5_TextChanged(object sender, EventArgs e)
{
if (System.Text.RegularExpressions.Regex.IsMatch(textBox5.Text, "[^0-9]"))
{
MessageBox.Show("SO NUMEROS!!!CRL.");
textBox5.Text = textBox5.Text.Remove(textBox5.Text.Length - 1);
}
}
private void Bubblesort()
{
int refos = 0;
for (int i=0;i<elementos.Length-1;i++)
{
for (int j = 0; j < elementos.Length - (i + 1); j++)
{
if (elementos[j] > elementos[j + 1])
{
refos = elementos[j];
elementos[j] = elementos[j + 1];
elementos[j + 1] = refos;
}
}
}
}
private void Button1_Click(object sender, EventArgs e)
{
Bubblesort();
for(int i=0;i<elementos.Length;i++)
{
lbOrdenada.Items.Add(elementos[i]);
}
}
}
}
Screenshot:
Problem so far: When we hit the "Ordenar" button, it shows 5 zeros.
You need to put the values from the text boxes into the elementos array. Because of the general messiness of the code, this can't be done elegantly, but something like this should do it:
private void Button1_Click(object sender, EventArgs e)
{
elementos[0] = Convert.ToInt32(TextBox1.Text);
elementos[1] = Convert.ToInt32(TextBox2.Text);
elementos[2] = Convert.ToInt32(TextBox3.Text);
elementos[3] = Convert.ToInt32(TextBox4.Text);
elementos[4] = Convert.ToInt32(TextBox5.Text);
Bubblesort();
for(int i=0;i<elementos.Length;i++)
{
lbOrdenada.Items.Add(elementos[i]);
}
}
This question already has answers here:
WinForm Application UI Hangs during Long-Running Operation
(3 answers)
Closed 6 years ago.
if I start my C# Windows Form Application, buttons hangs, because it is endless cycle. I want to see the change of variable value from button2 click into infinite loop of button1 through the global variable
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace XX_5
{
public partial class Form1 : Form
{
private int g;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int i = 0;
for (;;)
{
textBox1.AppendText("ID: [" + i++ + "] Variable value: [" + g + "]\n");
}
}
private void button2_Click(object sender, EventArgs e)
{
g = 1;
}
}
}
If you keep the infinite-loop in the button-click event handler, your application hangs definitely, since windows can't get / dispatch /process messages any more.
You can fix like the following:
private void button1_Click(object sender, EventArgs e)
{
int i = 0;
textBox1.AppendText("ID: [" + i++ + "] Variable value: [" + g + "]\n");
}
private void button2_Click(object sender, EventArgs e)
{
// int g = 1; // here you declare a local variable
g = 1; // use the member variable instead
}
Take a look at the Timer control (under the Components tab in the toolbox). You can put your code (without the for loop) in there and it will run every x milliseconds with the benefit that it will not hang. You will need to define your i variable at the form level when you do this. Your timer can then access this 'global variable'.
Something like this...
public partial class Form1 : Form
{
private int i = 0;
private int g = 0;
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
g = 1;
}
private void timer1_Tick(object sender, EventArgs e)
{
textBox1.AppendText("ID: [" + i++ + "] Variable value: [" + g + "]\n");
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
}
}
Im trying to make a cookie maker!
it works great and all but every time i click on the cookie, it takes it about 2 clicks to add just one to the cookie count. I want to make the counting system go faster, since if i click 2 times a second, it will only count as one atm...
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
namespace FormalCookie
{
public partial class Form1 : Form
{
int cnum = 0;
int add = 1;
public Form1()
{
InitializeComponent();
label1.Text = ("Price For Mouse:" + " 50");
textBox1.Text = ("Cookies:" + " " + cnum);
mouse.Enabled = false;
for (int i = 0; i< add; i++)
{
if (add > 1 && add % 2 == 0)
{
cnum += 1 * add;
}
Thread.Sleep(1000);
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
//Mouse
if (cnum >= add * add * 50)
{
cnum -= (add * 100);
add+=2;
}
}
private void button2_Click(object sender, EventArgs e)
{
Application.Restart();
}
private void button3_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
if (cnum >= (add * add * 50))
{
mouse.Enabled = true;
}
else
{
mouse.Enabled = false;
}
cnum += (add * add);
textBox1.Text = ("Cookies:" + " " + cnum);
label1.Text = ("Price For Mouse:" + " " + (add * add * 50));
}
private void label1_Click(object sender, EventArgs e)
{
}
private void pictureBox1_Click(object sender, MouseEventArgs e)
{
}
}
}
I have been following the C# tutorial at http://www.homeandlearn.co.uk/csharp/csharp_s2p17.html to make a calculator. I was doing just fine, following the instructions verbatim. I think they have to have an error in the tutorial or something because I have been pulling my freaking hair out trying to figure out why my calculator won't clear text when the + sign is clicked, (which, according to his tutorial, it's supposed to do -- right?)
Here is my code (Note the very bottom when I start to call the double variables, as this is where I "got lost"):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Calculator
{
public partial class calc : Form
{
public calc()
{
InitializeComponent();
}
private void btnOne_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnOne.Text;
}
private void btnTwo_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnTwo.Text;
}
private void btnThree_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnThree.Text;
}
private void btnFour_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnFour.Text;
}
private void btnFive_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnFive.Text;
}
private void btnSix_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnSix.Text;
}
private void btnSeven_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnSeven.Text;
}
private void btnEight_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnEight.Text;
}
private void btnNine_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnNine.Text;
}
private void btnZero_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnZero.Text;
}
private void btnClear_Click(object sender, EventArgs e)
{
txtDisplay.Clear();
}
double total1 = 0;
double total2 = 0;
private void btnPlus_Click(object sender, EventArgs e)
{
total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear();
}
private void btnEquals_Click(object sender, EventArgs e)
{
total2 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Text = total2.ToString();
total1 = 0;
}
}
}
Now, on the next page of the tutorial (http://www.homeandlearn.co.uk/csharp/csharp_s2p18.html), it asks me to add in the code for the equal button. It doesn't do anything it should when I run it. Namely, the textDisplay doesn't clear whatsoever when I hit the btnPlus button.
And I went through a lot of other questions attempting to find an answer before posting this. And no, this is not homework. It's a hobby actually.
I'm going crazy guys. Thanks in advance for any help you may be able to give me. I'm sure when this is figured out I'm going to want to slap myself.
In short: I would advice to look at debugging tool in Visual Studio. It will help you to understand what is going on when you click the buttons.
Here is a good and simple post to look - debugging tutorial
ReWrite the button again,then double click the buttoun from your form,after that try again to press + and see ,think will be sucesfull,wish you good luck
private void btnPlus_Click(object sender, EventArgs e)
{
total1 += total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear();
}
Just add a "+" before the "=" sign, and it will work.