I have a ASP.Net application that is a simple number generator. People guess, and it tells them whether or not they are correct. The issue I am having is in order to keep the randNum from changing each time the button is clicked to submit the answer (the page is reloaded), it is placed inside a Page.IsPostBack statement. The problem is the randomNum generated within this If is not accessible outside the If.
How can I get this variable accessable to other areas of my code while retaining the original randomNum? I want to use IsPostBack.
protected void btnGuess_Click(object sender, EventArgs e)
{
if (Page.IsPostBack == false) //the code only runs once when the form is loaded.
{
Random myGenerator = new Random();
myGenerator = new Random();
int randomNum = myGenerator.Next(1, 50);
}
else //code can always run
{
int guessedNum = Convert.ToInt32(txtGuess.Text);
if (guessedNum < randomNum)
{
MessageBox.Show("No. Low.");
txtGuess.Text = "";
}
else if (guessedNum > randomNum)
{
MessageBox.Show("No. High.");
txtGuess.Text = "";
}
else
{
MessageBox.Show("Yes");
txtGuess.Text = "";
}
}
}
Also, I have tried storing the variable as seen below:
HttpContext.Current.Session["RANDOM"] = randomNum;
and passing it to the else as:
int randomNum = Convert.ToInt32(HttpContext.Current.Session["RANDOM"]);
But doing this always results in a value of 0.
This is the only page that needs to use the variable. It does not need passed across pages, just functions.
Page.IsPostBack does not belong in a button click event. It needs to be added to Page_Load.
The way you have it now, it will always hit the else. i.e. it's always a postback in a button click.
protected void btnGuess_Click(object sender, EventArgs e)
{
int randomNum = Convert.ToInt32(HttpContext.Current.Session["RANDOM"]);
int guessedNum = Convert.ToInt32(txtGuess.Text);
if (guessedNum < randomNum)
{
MessageBox.Show("No. Low.");
txtGuess.Text = "";
}
else if (guessedNum > randomNum)
{
MessageBox.Show("No. High.");
txtGuess.Text = "";
}
else
{
MessageBox.Show("Yes");
txtGuess.Text = "";
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false) //the code only runs once when the form is loaded.
{
Random myGenerator = new Random();
myGenerator = new Random();
int randomNum = myGenerator.Next(1, 50);
HttpContext.Current.Session["RANDOM"] = randomNum;
}
}
Related
I have a list
static List<Participants> soop = ParticipantRepository.GetAllParticipants();
It has some 800 items. Then there's a label and a timer. At timer_tick, I want to display one of the items randomly. Here's the code for that event
private void timer1_Tick(object sender, EventArgs e) {
foreach (var participants in soop)
{
a = participants.RollNumber;
label1.Text = a;
break;
}
counter++;
if (counter == 200) {
timer1.Stop();
pictureBox5.Visible = false;
counter = 0;
}
}
I have not been able to achieve the random functionality so far because only one RollNumber is being displayed and then the timer takes its time and runs out. What am I doing wrong?
I would suggest using the random class.
Random randomGen = new Random();
private void timer1_Tick(object sender, EventArgs e)
{
var i = randomGen.Next(0, soop.Count);
label1.Text = soop[i].RollNumber;
counter++;
if (counter == 200)
{
timer1.Stop();
pictureBox5.Visible = false;
counter = 0;
}
}
At each tick the timer1_Tick is called, so your foreach loop starts back from the beginning and you end up displaying the first item every time. Instead, you can store the index of the last item you displayed. You already have counter so let's use it:
private void timer1_Tick(object sender, EventArgs e)
{
label1.Text = soop[counter % soop.Count].RollNumber;
counter++;
if (counter == 200) {
timer1.Stop();
pictureBox5.Visible = false;
counter = 0;
}
}
I have a counter that onclick should increment 1 and it does that on click, but if I click the button again, it won't increment again. Instead it will be stuck at 1. How can I make it go up if the button is clicked more than once?
protected void submitAnswerButton_Click(object sender, EventArgs e)
{
int counter = 0;
if (mathAnswerTextBox.Text == answer.ToString())
{
answerStatus.Text = "Correct!";
}
else if (mathAnswerTextBox.Text != answer.ToString())
{
answerStatus.Text = "Incorrect";
counter++;
if (counter == 1)
{
incorrectStrikes.Text = counter.ToString();
}
else if (counter == 2)
{
incorrectStrikes.Text = counter.ToString();
}
else if (counter == 3)
{
incorrectStrikes.Text = counter.ToString();
}
}
You would need to make counter outside of the method, such as a field in the class, not a local variable:
private int counter = 0;
protected void submitAnswerButton_Click(object sender, EventArgs e)
{
if (mathAnswerTextBox.Text == answer.ToString())
{
answerStatus.Text = "Correct!";
...
Since this is a web application you'd probably want to store the counter in the session, something like:
Inside Page_Load:
if(!IsPostback)
{
Session["AttemptCount"] = 0
}
And then inside
protected void submitAnswerButton_Click(object sender, EventArgs e)
{
int counter = (int)Session["AttemptCount"];
if (mathAnswerTextBox.Text == answer.ToString())
{
answerStatus.Text = "Correct!";
...
//Make sure you include this on all paths through this method that
//affect counter
Session["AttemptCount"] = counter;
As it stands you counter is a local variable (as in below code) and so every time you click button it will get initialized to 0 and hence you get 1 every time cause it's getting incremented once.
protected void submitAnswerButton_Click(object sender, EventArgs e)
{
int counter = 0;
You'll need to store the value in a more global context, eg ViewState or Session or maybe even a HiddenField for storage of the value.
Conclusio: Web is stateless so you'd need a state-manager.
protected void submitAnswerButton_Click(object sender, EventArgs e)
{
var counter = this.ViewState["foo"] as int; // read it from the ViewState from the previous request, or set it to default(int) = 0 with as
// ... do your routine
this.ViewState["foo] = counter; // write it back to store it for the next request
}
Anyway - this is just valid in a web-context where you are stateless.
If you were in a webform/wpf-context you would rather go for a simple static, or instance-variable, or ... (whatever suits your current need, architecture, ...)
I'm trying to display an image using a button click and increment a variable when a certain image is shown, but with the code below the variable num is always 0.
my code
int num = 0;
int i = 0;
int x = 0;
PictureBox[] pictureBoxs = new PictureBox[4];
Random rnd = new Random();
public UserControl1()
{
InitializeComponent();
pictureBoxs[0] = pbimg1;
pictureBoxs[1] = pbimg2;
pictureBoxs[2] = pbimg3;
pictureBoxs[3] = pbimg4;
x = rnd.Next(2);
}
public void displaypics()
{
pictureBoxs[i].Image = imageList1.Images[x];
}
private void btn2_Click(object sender, EventArgs e)
{
i=1;
displaypics();
if (pictureBoxs[i].Image == imageList1.Images[1])
{
num++;
}
if (num == 2)
{
tb1.Visible = true;
tb1.Text = "GAME OVER!" + num;
}
}
The reason is most likely that num is being instantiated to zero everytime the class is being instantiated
What happens when you set breakpoints and step through the code? Is the int set as 0, or does it contain the updated value?
I'm not sure what the context is in which that piece of code is used. So I guess what should solve this would be adding x = rnd.Next(2) to the btn2_Click method. Making it look like this:
private void btn2_Click(object sender, EventArgs e)
{
x = rnd.Next(2);
displaypics();
if (pictureBoxs[i].Image == imageList1.Images[1])
{
num++;
}
if (num == 2)
{
tb1.Visible = true;
tb1.Text = "GAME OVER!" + num;
}
i++;
}
Maybe you could give some more details on what that control should do/how it's used.
i'm new to C# (and programming at all) and i'm trying to write an 'XO' game along with ASP.NET
i'm getting a problem after the first player clicks a button.
turns doesn't switch and any click after the 1st does nothing. what is wrong with my code ?
public partial class GamePage : System.Web.UI.Page
{
Player player1 = new Player();
Player player2 = new Player();
int turn;
protected void Page_Load(object sender, EventArgs e)
{
this.turn = 0;
if (!IsPostBack)
{
Label1.Visible = true;
}
if (turn == 0)
{
Label1.Text = (Session["player1"] as Player).getname();
}
else
{
Label1.Text = (Session["player2"] as Player).getname();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Session["p1"] = player1;
Session["p2"] = player2;
player1.setsymbol("X");
player2.setsymbol("O");
if (Button1.Text == "")
{
if (turn == 0)
{
Button1.Text = player1.getsymbol();
Label1.Text = (Session["player2"] as Player).getname();
turn = 1;
}
else
{
Button1.Text = player2.getsymbol();
Label1.Text = (Session["player1"] as Player).getname();
turn = 0;
}
}
}
protected void Button2_Click(object sender, EventArgs e)
{
if (Button2.Text == "")
{
if (turn == 0)
{
Button2.Text = player1.getsymbol();
Label1.Text = (Session["player2"] as Player).getname();
turn = 1;
}
else
{
Button2.Text = player2.getsymbol();
Label1.Text = (Session["player1"] as Player).getname();
turn = 0;
}
}
}
protected void Button3_Click(object sender, EventArgs e)
{
if (Button3.Text == "")
{
if (turn == 0)
{
Button3.Text = player1.getsymbol();
Label1.Text = (Session["player2"] as Player).getname();
turn = 1;
}
else
{
Button3.Text = player2.getsymbol();
Label1.Text = (Session["player1"] as Player).getname();
turn = 0;
}
}
}
// this is an example - i have the same lines from button1 to 9
Everytime page renders, you set turn to 0 in Page_Load. Because Page_Load is executed upon every page load, you won't get any other value and this is probably the major issue here.
To properly support the lifetime of such variables that should keep value upon consecutive requests, wrap them in simple property:
public int turn
{
get
{
if ( Session["turn"] != null )
return (int)Session["turn"];
return 0; // default value if not set before
}
set
{
Session["turn"] = value;
}
}
This way everytime you refer to turn in your code, setting it to 0 or 1 or comparing the value to 0 or 1, you will refer to the same value, possibly stored during previous request(s).
this.turn=0; should be executed only when IsPostBack is false. Move this line inside if in your Page_Load.
I don't know how to add a value in a textbox.
This is the code:
private void starecivilaComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (starecivilaComboBox.SelectedIndex == 0)
{
MessageBox.Show("This selection is not valid!");
}
else if (starecivilaComboBox.SelectedIndex == 1)
{
int score = 4;
}
else if (starecivilaComboBox.SelectedIndex == 2)
{
int score = 1;
}
else if (starecivilaComboBox.SelectedIndex == 3)
{
int score = 3;
}
else if (starecivilaComboBox.SelectedIndex == 4)
{
int score = 2;
}
}
I want to insert the value of score in a textbox, so it will show me the score of each item i've selected from combobox.
I tried with this:
private void scoringTextBox_TextChanged(object sender, EventArgs e)
{
scoringTextBox.Text = score.toString();
}
But it doesn't recognize it. The error is: The name 'score' does not exist in this context. How can I make this work ?
Thank you.
You must declare variable score outside of ComboBox SelectedIndexChanged handler. You're declaring it in the handler and it's being used only in the method, not in the whole class (not in the whole form in your case).
public class Form1
{
int score = 0;
//somewhere in the code
score = 1; //there is no need to specify 'int' here - you will create an local variable with the same name then
}
I recommend you to learn through tutorials, because the question is rather simple.
Though #psNytrancez answer is the simplest for you, you will not get far in C# without understanding how variables work.
The problem is with the lines that look like this:
else if (starecivilaComboBox.SelectedIndex == 1)
{
int score = 4;
}
it means that you create a variable "score", but that the variable will only exists between the two braces "{" and "}". In order to actually keep a value, you need to expand its scope (instruction video). if you edit all those lines to just read
else if (starecivilaComboBox.SelectedIndex == 1)
{
score = 4;
}
and instead put it outside the method declaration like this
int score =0;
private void starecivilaComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
//the rest of the method.
then you should be fine.
It is because you are declaring your score inside of the starecivilaComboBox_SelectedIndexChanged method so it is local to that method and cannot be accessed outside of it.
As stated above, you must declare score outside of your private method but inside your class. Code should look similar to this:
private int score = 0;
private void starecivilaComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (starecivilaComboBox.SelectedIndex == 0)
{
MessageBox.Show("This selection is not valid!");
}
else if (starecivilaComboBox.SelectedIndex == 1)
{
score = 4;
}
else if (starecivilaComboBox.SelectedIndex == 2)
{
score = 1;
}
else if (starecivilaComboBox.SelectedIndex == 3)
{
score = 3;
}
else if (starecivilaComboBox.SelectedIndex == 4)
{
score = 2;
}
}
private void scoringTextBox_TextChanged(object sender, EventArgs e)
{
scoringTextBox.Text = score.toString();
}
private void starecivilaComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (starecivilaComboBox.SelectedIndex == 0)
{
MessageBox.Show("This selection is not valid!");
}
else if (starecivilaComboBox.SelectedIndex == 1)
{
scoringTextBox.Text = "4";
}
else if (starecivilaComboBox.SelectedIndex == 2)
{
scoringTextBox.Text = "1";
}
else if (starecivilaComboBox.SelectedIndex == 3)
{
scoringTextBox.Text = "3";
}
else if (starecivilaComboBox.SelectedIndex == 4)
{
scoringTextBox.Text = "2";
}
}
Do it after this
else if (starecivilaComboBox.SelectedIndex == 4)
{
int score = 2;
}
Add this
scoringTextBox.Text = score.toString();
The scope for variable / object score is the problem
you are trying to access a variable that has limited scope (function level only)
simply create a private variable score so it can be accessed through the class.