saving variables between page refresh - c#

i need to do a basic web page (homework)
the user need to input number into textbox. after every number he need to press the "enter number" button.
and after a few numbers he need to press a different button to display his number and some calculations.
i cant use arrays ( homework limitations).
the problem is that after every time the user press "enter number" , the variables reset.
what can i do?
here's the code:
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 WebForm1 : System.Web.UI.Page
{
int totalSum=0;
int mulOdd=1;
int small=0;
int big=0;
float avg=0;
int pairsum=0;
int counter = 0;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
int t;
counter++;
t = Convert.ToInt16(TextBox1.Text);
totalSum = totalSum + t;
avg = totalSum / counter;
int odd = t % 2;
if (odd > 0)
{
mulOdd = mulOdd * t;
}
else
{
pairsum = pairsum + t;
}
if (t < small)
{
small = t;
}
if (t > big)
{
big = t;
}
TextBox1.Text = " ";`enter code here`
Label1.Text = Convert.ToString(counter);
}
protected void Button2_Click(object sender, EventArgs e)
{
Label1.Text = "total Sum" + Convert.ToString(totalSum);
}
}
}
thank you.

You need to save the variables in state. There are several ways to pass variables
[1] Cookies (rarely found use for this)
[2] Session (Good for storing between pages for a different user)
[3] ViewState (Same page saving for a user)
[4] Query Strings (passing between pages)
Have a read about these and this should do the trick. Forgive me if i missed some out.

You need to read about the page life cycle and about state management, in particular view state.

It's difficult to help without knowing the conditions of your assignment, but a method that would be usable would be to have a hidden field (webusercontrol) on the page that would hold a string. Each time the button is clicked, append the string representation of the number to the value of that control, making sure to separate the values with a symbol (comma, #, |, anything will do really). Then at any point during the process you would be able to get the value of that control, split it on the character, and compute whatever you needed to compute.
Since this is identified as homework, I won't be posting code, but this process should be pretty straight-forward.

In your page load event, check the Page.IsPostback property. If true, then reset your variables based on the user input from the server controls HTML markup.
Read the links provided by #Oded. Page life cycle is a very important topic.

Some pointers that you could extend to all your variables...
Remove the global declaration of all of these variables, you don't need to have a global scope for them:
int totalSum=0;
int mulOdd=1;
int small=0;
int big=0;
float avg=0;
int pairsum=0;
int counter = 0;
On Button1_Click store the totalSum as so:
ViewState["Sum"] = Convert.ToInt16(string.IsNullOrEmpty(ViewState["Sum"])?"0":ViewState["Sum"].ToString() )+ Convert.ToInt16(TextBox1.Text);
Finally, on Button_Click2 do:
Label1.Text = "total Sum" + Convert.ToString(string.IsNullOrEmpty(ViewState["Sum"])?"0":ViewState["Sum"].ToString());

Related

Add timer to idle game

Ok, so as I go through learning C# I have run into an issue that I can't quite wrap my mind around.
I am building an idle game to learn more than books have taught me. Anyways, I am adding an "Auto-clicker" function. I thought that I should add a timer that would count to 1 second and add gold to the player's score. Maybe this is not the best way to approach this, but here is what I have so far:
Updated Code as per requested with Errors trying to load System.Timers.Timer;
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.Timers;
namespace IdleClicker1
{
public partial class Form1 : Form
{
public double gold = 0;
public double goldPerClick = 1;
public double upgradeCost = 20;
public double autoMinerLevel = 0;
public double autoMinerCost = 10;
public System.Timers.Timer autoMineTimer = new System.Timers.Timer();
public Form1()
{
InitializeComponent();
}
private void btnGetGold_Click(object sender, EventArgs e)
{
gold += goldPerClick;
updateGoldShown();
}
public void updateGoldShown()
{
lblGold.Text = "Gold: " + gold.ToString();
lblGoldPerClick.Text = "Gold per click: " + goldPerClick.ToString();
lblAutoMiner.Text = "Auto-Miner Level: " + autoMinerLevel.ToString();
}
private void btnUpgradeClick_Click(object sender, EventArgs e)
{
if (gold >= upgradeCost)
{
gold = gold - upgradeCost;
goldPerClick = goldPerClick + 1;
upgradeCost = upgradeCost + 10;
lblUpgradeCost.Text = "Cost to upgrade: " + upgradeCost.ToString();
updateGoldShown();
}
else
{
MessageBox.Show("Sorry bub... not enough gold yet!", "Error buddy!");
}
}
public void btnAutoMiner_Click(object sender, EventArgs e)
{
if (gold >= autoMinerCost)
{
autoMinerLevel++;
gold = gold - autoMinerCost;
autoMinerCost = autoMinerCost + 10;
btnAutoMiner.Text = "Buy Auto-Miner for: " + autoMinerCost.ToString();
updateGoldShown();
//Adding a new timer
System.Timers.Timer autoMineTimer = new System.Timers.Timer();
autoMineTimer.Tick += new EventHandler(timer_Tick);
autoMineTimer.Interval = 1000;
autoMineTimer.Enabled = true;
autoMineTimer.Start();
}
else {
MessageBox.Show("Sorry... not enough gold!", "Error again... yo!");
}
}
void timer_Tick(object sender, EventArgs e)
{
updateGoldShown();
btnGetGold.PerformClick();
}
}
}
Basically, this is a very simple setup. I am just trying to learn by practice and applying myself. So when the user clicks on btnAutoMiner, it should start a timer that would add whatever the goldPerClick to the player's gold. I don't want an exact answer (otherwise I will never learn), but can someone abstractly help me out?
I'm not sure what the point of the timer is. Do you want to run btnAutoMiner_Click each second or on each click? If you add on each click, what is the point of the timer? Sorry, it's just a bit hard to understand your goals.
Here is the timer documentation in case you needed it.
Edit: to perform a click from the timer, you can you use .PerformClick to simulate a click.
I mean this with the deepest respect but have you tried using the debugger and breakpoints to check if everything unfolds as expected.
I took the liberty to recreate your program, making a form that fits your code and what I got was a functional program that behaved as you described, when I click GetGold my gold increases by the goldPerClick value as expected, same with the UpgradeClick.
As I clicked Buy Auto-Miner I had a breakpoint at the buttons event method, the level went up by 1 as expected and the timer started just fine, again with a breakpoint I was monitoring the timers event method, which was called once per second as expected, so conclusion is that your program behaves just as its expected to logically.
However for the GUI there is a bit of a problem, the values is not being updated as the timer ticks so I would suggest looking there first, also some labels/buttons texts is only updated when certain buttons are clicked so again I would suggest putting all those in the same place and just call that method when needed.
Just some friendly design advice as well (without being too specific):
Consistency is important for good design, this means either use value1 += value2 or value1 = value1 + value2 both is equally as right but mostly for consistency.
Using the right value types, using int values for simple numbers like 10 (sbyte, byte, short, ushort, int, uint, or char) and use floating point values for values like 1.5 (Double, Float)
I really hopes these tips helps you along your way and good luck with the project.
Assuming that your GetGold button is working as you expect it to, you can programatically trigger it's click handler:
btnGetGold.PerformClick();
You would put this code inside the tick event handler for your Timer.

Logic trouble with loop

I am creating a windows form that is a random number guessing game. I've made these before in C++ and never had an issue, however I have a big one here- I have no idea how to get the user back to input a number after the loop has began running. Here is my code:
private void btnGuess_Click(object sender, EventArgs e)
{
int guess = 0;
int count = 0;
int accumulator = 0; // accumulator
Random rand = new Random();
int number = rand.Next(1, 100);
txtAnswer.Focus();
while (guess != number)
{
guess = int.Parse(txtAnswer.Text);
if (guess < number)
{
MessageBox.Show("Too Low! Guess again!");
txtAnswer.Text = "";
txtAnswer.Focus();
count++;
accumulator++;
}
else if (guess > number)
{
MessageBox.Show("Too High! Try again!");
txtAnswer.Text = "";
txtAnswer.Focus();
count++;
accumulator++;
}
else
{
MessageBox.Show("Correct! you guessed the number in " + accumulator + " tries!");
break;
}
}
}
}
}
I just filled the while loop arguments with something for you guys, even though i know it won't work. Basically, I need to run the loop, get feedback (if the users guess was too high or low) then get the user to be able to input another number BEFORE the loop runs again. I don't know how to get that to happen with a text box control which is where the input will be. Any ideas?
You should not loop inside in the btnGuess_Click. Instead you need to store the state (the number, count, and the accumulator variables) in the scope of the form itself.
Initialize the random number when the form loads, or using some kind of start button.
Then inside the guess button handler, read the text box value and compare it to the number variable, such as what you are doing currently.
What you are building is more a console style application. So there is 1 main loop that is executing all the code.
In forms applications it is an event driven environment. So the user gets a form, presses a button, the form is evaluated and then the method handling ends.
So you have on a class level some variables for counts, in the constructor you add the initialization and the method for submit will be something like
private void btnGuess_Click(object sender, EventArgs e)
{
//Increment counters
//Check
//Show feedback
//Leave the button click code
}
For some more info, check this out:
https://msdn.microsoft.com/en-us/library/dd492132.aspx

Passing arrays to a method inside event C#

Im trying to create a section of a program, where a user presses a button and a image is placed in one of 9 pictureboxes. Each time the button is clicked, a different picturebox should be selected. However, before i get to that, i'm having trouble getting my method to see the arrays i am trying to pass it.
I have 2 arrays, Slots and SlotsUsed and i am trying to initalise them when the program starts. However, when i try to pass them to the method "randomBox" which is called within "Button1" visual studio says they do not exist. How can i make these arrays visible throughout my code?
Many thanks
Anthony
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 pin_program
{
public partial class Mainscreen : Form
{
//Sets where users files are to be stored (for later use)
string activeDir = #"C:\Users\Tony\Downloads\Programs\pin program\Users";
public Mainscreen()
{
InitializeComponent();
}
//method to generate random number
private int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
public void randomBox(int pictureVal, PictureBox[] Slots, bool[] SlotsUsed)
{
//generate random number
int j = RandomNumber(0, 9);
if (SlotsUsed[j] == false)
{
// Create image, assign it and set slots value to used
Image newImage = Image.FromFile(#"C:\Users\Tony\Downloads\Programs\pin program\pin program\pin program\Images\" + pictureVal + ".jpg");
Slots[j].Image = newImage;
SlotsUsed[j] = true;
}
else
do
{
j = RandomNumber(0, 9);
} while (SlotsUsed[j] == false);
return;
}
private void button1_Click(object sender, EventArgs e)
{
//for use later
string userName = textBox1.Text;
//for use later
label1.Visible = true;
//test call of method.
randomBox(1, Slots, SlotsUsed);
}
public void Mainscreen_Load(object sender, EventArgs e)
{
//array for slots
PictureBox[] Slots = new PictureBox[9];
Slots[0] = pictureBox1;
Slots[1] = pictureBox2;
Slots[2] = pictureBox3;
Slots[3] = pictureBox4;
Slots[4] = pictureBox5;
Slots[5] = pictureBox6;
Slots[6] = pictureBox7;
Slots[7] = pictureBox8;
Slots[8] = pictureBox9;
//array for used slots
bool[] SlotsUsed = new bool[9];
for (int i = 0; i != (SlotsUsed.Length); i++)
{
SlotsUsed[i] = false;
}
}
}
}
EDIT:
I dont seem to be able to post comments for some reason, so i'll just ask here. How would i declare my arrays as instance variables instead of local? Does instance variable have another name i might know it by?
CHeers
Currently you're declaring Slots and SlotsUsed as local variables in Mainscreen_Load. They need to be instance variables in your form, as otherwise you can't refer to them elsewhere - and indeed they won't logically exist elsewhere. They're part of the state of your form, so they should be instance variables.
Additionally, your approach for generating random numbers is broken - see my article on random numbers for more information.
I'd also add that you might consider just using a single collection, shuffling it to start with, and then removing items from it as you go - that way you can easily tell when you've run out of images, and you don't have to loop round until you find an unused slot.
well, the easiest way to do this would be to declare a field.
protected PictureBox[] Slots
inside your Form class (outside of any methods.

C# textbox user input processed by a button object [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C# GUI application that stores an array and displays the highest and lowest numbers by clicking a button
This is updated from 13 hours ago as I have been researching and experimenting with this for a few. I'm new to this programming arena so I'll be short, I'm teaching myself C# and I'm trying to learn how to have integers from a user's input into a textbox get calculated from a button1_Click to appear on the form. Yes, this is a class assignment but I think I have a good handle on some of this but not all of it; that's why I'm turning to you guys. Thanks for all of the advice guys.
I'm using Microsoft Visual Studio 2010 in C# language. I'm using Windows Forms Application and I need to create a GUI that allows a user to enter in 10 integer values that will be stored in an array called from a button_Click object. These values will display the highest and lowest values that the user inputted. The only thing is that the array must be declared above the Click() method.
This is what I have come up with so far:
namespace SmallAndLargeGUI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void inputText_TextChanged(object sender, EventArgs e)
{
this.Text = inputText.Text;
}
public void submitButton_Click(object sender, EventArgs e)
{
int userValue;
if(int.TryParse(inputText.Text, out userValue))
{
}
else
{
MessageBox.Show("Please enter a valid integer into the text box.");
}
int x;
x = Convert.x.ToString();
int squaredResults = squared(x);
int cubedResults = cubed(x); squared(x);
squaredLabel.Text = x.ToString() + " squared is " + squaredResults.ToString();
cubedLabel.Text = x.ToString() + " cubed is " + cubedResults.ToString();
}
public static int squared(int x)
{
x = x * x;
return x;
}
public static int cubed(int x)
{
x = x * squared(x);
return x;
}
}
}
Now I can't run this program because line 38 shows an error message of: 'System.Convert' does not contain a definition for 'x' Also I still have to have an array that holds 10 integers from a textbox and is declared above the Click() method. Please guys, any help for me? This was due yesterday.
As a couple of comments have mentioned, there really isn't enough information here to provide you with a useful answer. There are two main User Interface frameworks in .Net for windows applications. One of these is commonly referred to as "WinForms" and the other is "WPF" or "Windows Presentation Foundation."
I'm going to go with you are most likely using WinForms as it is the older of the two technologies. The approach here can be used on both sides with a little tweaking. Setting text in a text box is very similar to setting text programaticly on a label. You can get more detail on that on MSDN: How to: Display Text on a Windows Form; How to: Use TextBox Controls to Get User Input.
If you are using WPF the "back end" code is pretty much the same. You just need to make sure your textbox has an x:Name="userInputTextBox" so you can reference it in your code behind. Be mindful that your users can input "1", "3" or "abcd" in the field. Ensuring your app doesn't bomb is most likely outside of the assignment but feel free to look up C# int.TryParse(...) and "Try Catch" :-)
Your button handler could look like this:
void btnUserClick_Click(object sender, System.EventArgs e)
{
int userValue;
if(int.TryParse(txtUserInput.Text, out userValue))
{
// We have the value successfully, do calculation
}
else
{
// We don't have the users value.
MessageBox.Show("Please enter a valid integer into the text box.")
}
}
In your retrieveInput_Click handler you are assigning the min/max numbers to a local int. Once you determine your min/max numbers in the logic, you will need to assign those local integers to a UI element for display.
Since we don't have any details on your specific UI choices, one simple solution could be to add 2 labels to your form, and then in the code you would place the result in the label:
for (int i = 0; i < numbers.Length; ++i)
{
if (numbers[i] < min)
min = numbers[i];
if (numbers[i] > max)
max = numbers[i];
}
// Assign Minimum to Label1
Label1.Text = "Minimum Value: " + min.ToString();
// Assign Maximum to Label2
Label2.Text = "Maximum Value: " + max.ToString();
define the textbox named textbox1 or txt_name
you can write the button1_Click function :
int i_value = Convert.ToInt16(txt_name.Text);
ok. I haven't try catch the exceptions.... :(
maybe above answer is right.
btw, i think this question mainly focus on how to get int type from text box. right?

Why with some browsers i get a wrong value for my Session object?

I am coding an asian language learning module for my mojoportal-based iphone-optimized website (work in progress, english resources are not fully translated: http://ilearn.dandandin.it/kanatrainer.aspx)
It's a simple "guess how to read this" game, with the right answer stored in a Session object.
I don't understand why, but, expecially using Safari, users will get someone else's Session value
This is an excerpt from the code (i removed some stuff, translated the variables)
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
...
generateRandom();
}
}
protected void generateRandom()
{
int i, j = 0, livello = 5, chance = 0;
System.Random acaso = new Random();
...
while (j <= 0)
{
j = acaso.Next((Convert.ToInt32(TextBoxlunghezza.Text) + 1));
}
...
for (int k = 0; k < j; k++)
{
i = acaso.Next(livello);
Session["randomLetters"] += (globals.asianCharacters[i]);
...
}
...
}
protected void AnswerButton_Click(object sender, EventArgs e)
{
string compare = Server.HtmlEncode(InputTextBox.Text.ToLower());
if (compare == "")
{
Label1.Text = ("You did not write anything");
return;
}
if (Session["randomLetters"].ToString() != compare)
{
Label1.Text = ("Wrong!" + Session["randomLetters"]);
}
else
{
Label1.Text = ("Right!" + Session["randomLetters"]);
}
...
}
What happens in visual studio, with every browser:
randomLetters is "hello". User writes "hello" in the textbox, and "hello" is compared to "hello". Label says "Right! hello".
What happens in iis, only in webkit-based browsers:
randomLetters is "hello". User writes "hello" in the textbox, but "hello" is compared to "goodbye". Label says "Wrong! goodbye".
I don't understand how Session["randomLetters"] has changed
Public vs private code:
How are your storing the session state? Cookie? Database? so on... I have had many problems (usually with IE 8) with the way that the browser was caching the pages and the cookies. Usually, changing the respective setting in the browser fixed the problem. I don't know if that helps here. To make it more robust, I then have to find a way to notify the user when one of these settings is not right.
Using HiddenFields i "solved" the problem (but i don't like that way)

Categories

Resources