if(!IsPostback) doesn't exist in the current context - c#

I'm building a web application using a webform and I'm trying to store a counter in a Session, but I'm getting the error that if(!IsPostback) doesn't exist in the current context. Can anyone help me with this issue?
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostback)
{
Session["AttemptCount"] = 0;
}
}
protected void submitAnswerButton_Click(object sender, EventArgs e)
{
//difficultyList.SelectedIndex = 2;
answerStatus.Visible = true;
int answer = randomNumber1 + randomNumber2;
int counter = (int)Session["AttemptCount"];
if (mathAnswerTextBox.Text == answer.ToString())
{
counter++;
Session["AttemptCount"] = counter;
answerStatus.Text = "Correct!";
// scoreLabel.Text = "Score: " + counter.ToString();
randomNumber1 = random.Next(0, 50);
randomNumber2 = random.Next(0, 50);
num1Label.Text = Convert.ToString(randomNumber1);//add this line
num2Label.Text = Convert.ToString(randomNumber2); //and this line
num1Label.Visible = true;
num2Label.Visible = true;
mathAnswerTextBox.Visible = true;
submitAnswerButton.Visible = true;
}
else if (mathAnswerTextBox.Text != answer.ToString())
{
answerStatus.Text = "Incorrect";
incorrectStrikes.Text = counter.ToString();
num1Label.Visible = true;
num2Label.Visible = true;
mathAnswerTextBox.Visible = true;
submitAnswerButton.Visible = true;
// scoreLabel.Text = counterArray[0].ToString();
}

As I previously mentioned in my comment to your question, your original problem was with the lowercase b in Postback. The reason your "AttemptCount" session variable is not being incremented is because your if statement only increments it:
if (mathAnswerTextBox.Text == answer.ToString())
I think you want to do this in the else clause of your if statement, and not when the answer is correct.

Related

Why are the values still adding up after i clear the output label?

I'm not sure what is going on. I thought I had it set up to clear the output label at the end. Everytime I clear it, the program still remembers the previous number and adds to it. I honestly have no idea what is going on.
Also on a side note, how do I put set up radiobuttons to be used in the this method?
First coding class so i'm still kind of a beginner.
private double oilandlube()
{
if (checkBox1.Checked == true)
{
Oil_change = 26;
}
if (checkBox2.Checked == true)
{
Lube_job = 18;
}
return Oil_change + Lube_job;
}
private void Oiltype ()
{
if (radioButton1.Checked)
{
Regular = 0;
}
if (radioButton2.Checked)
{
Mixed = 10;
}
else
{
Mixed = 0;
}
if (radioButton3.Checked)
{
Full_Synthetic = 18;
}
else
{
Full_Synthetic = 0;
}
}
private void carwash()
{
if (radioButton4.Checked)
{
none = 0;
}
if (radioButton5.Checked)
{
complimentary = 0;
}
if (radioButton6.Checked)
{
Full_service = 6;
}
else
{
Full_service = 0;
}
if (radioButton7.Checked)
{
Premium = 9;
}
else
{
Premium = 0;
}
}
private double flushes()
{
if (checkBox3.Checked == true)
{
Radiator_flush = 30;
}
if (checkBox4.Checked == true)
{
Transmission_flush = 80;
}
return Radiator_flush + Transmission_flush;
}
private double misc()
{
if (checkBox5.Checked == true)
{
inspection = 15;
}
if (checkBox6.Checked == true)
{
replace_muffler = 100;
}
if (checkBox7.Checked == true)
{
tire_rotation = 20;
}
return inspection + replace_muffler;
}
private double partsandlabor()
{
double.TryParse(textBox1.Text, out parts);
double.TryParse(textBox2.Text, out labor);
return parts + labor;
}
private double tax()
{
return partsandlabor() * taxes;
}
private void summary()
{
service = oilandlube() + flushes() + misc();
total_parts = partsandlabor();
double total_tax = tax();
double grand_total = service + total_parts + total_tax;
label7.Text = service.ToString("c");
label8.Text = total_parts.ToString("c");
label9.Text = total_tax.ToString("c");
label10.Text = grand_total.ToString("c");
}
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
oilandlube();
carwash();
flushes();
misc();
partsandlabor();
summary();
}
private void ClearOilandlube()
{
checkBox1.Checked = false;
checkBox2.Checked = false;
}
private void ClearMisc()
{
checkBox5.Checked = false;
checkBox6.Checked = false;
checkBox7.Checked = false;
}
private void ClearFlushes()
{
checkBox3.Checked = false;
checkBox4.Checked = false;
}
private void ClearSummary()
{
label7.Text = "";
label8.Text = "";
label9.Text = "";
label10.Text = "";
}
private void button2_Click(object sender, EventArgs e)
{
ClearOilandlube();
ClearMisc();
ClearFlushes();
ClearSummary();
radioButton1.Checked = false;
radioButton2.Checked = false;
radioButton3.Checked = false;
radioButton4.Checked = false;
radioButton5.Checked = false;
radioButton6.Checked = false;
radioButton7.Checked = false;
textBox1.Text = "0";
textBox2.Text = "0";
}
}
}
When you clear the contents of your controls, you should also clear the values of the backing variables, so they don't retain their previous values. You should be able to just set them back to zero in your Clear methods.
For example, oil and lube might look like:
private void ClearOilandlube()
{
checkBox1.Checked = false;
checkBox2.Checked = false;
Oil_change = 0;
Lube_job = 0;
Mixed = 0;
Regular = 0;
Full_Synthetic = 0;
}
It looks like you're holding state of some your variables globally so you can access them elsewhere.
Mixed = 10;
You'll have to reset that to some default value as well.

Stopping the calculations because of predicted error

I am unsure how to ask this question as I can't quite well translate it.
I am currently working on my own Windows Form Application that will calculate the dimensions of a given package in inches (written all together in string format) and calculate the dimensions in centimeters, milimeters or even meters and at this point I was wondering what if someone entered wrong dimensions and given measures can not be parsed.
Something like Environment.Exit(), but without closing the application just stopping calculations and writing a message that an error has occured.
If there is a question like this answered, please do link it because I haven't been able to find it.
namespace PretvaranjeDimenzija
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public double mjera = 1;
public bool pogreska = false;
public string mjeraKratica = " cm";
public string dimenzijeIspis = "";
private void buttonIzracunaj_Click(object sender, EventArgs e)
{
string dim = textBoxDimenzije.Text;
if (dim.Contains('.'))
{
dim = dim.Replace('.', ',');
}
if (dim.Length != 0)
{
if (dim.IndexOf('x') != -1)
{
string[] multiDim = dim.Split('x');
double[] multiDimCentimetara = new double[multiDim.Length];
bool[] uspjeh = new bool[multiDim.Length];
for (int i = 0; i < multiDim.Length; i++)
{
uspjeh[i] = double.TryParse(multiDim[i], out multiDimCentimetara[i]);
if (uspjeh[i] == false)
{
pogreska = true;
goto kraj;
}
}
kraj:
if (pogreska == true)
{
MessageBox.Show("Doslo je do pogreske!");
pogreska = false;
}
else
{
double[] dimenzije = new double[multiDim.Length];
for (int i = 0; i < dimenzije.Length; i++)
{
dimenzije[i] = multiDimCentimetara[i] * 2.54 * mjera;
if (i == dimenzije.Length - 1)
{
dimenzijeIspis += dimenzije[i].ToString() + mjeraKratica;
}
else
{
dimenzijeIspis += dimenzije[i].ToString() + "x";
}
}
textBoxIspisDimenzija.Text = dimenzijeIspis;
dimenzijeIspis = "";
}
}
else
{
double dimCentimetara;
if(double.TryParse(dim, out dimCentimetara))
{
double dimenzija = dimCentimetara * 2.54 * mjera;
dimenzijeIspis = dimenzija.ToString() + mjeraKratica;
textBoxIspisDimenzija.Text = dimenzijeIspis;
dimenzijeIspis = "";
}
else
{
MessageBox.Show("Doslo je do pogreske!");
return;
}
}
}
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
mjera = 0.01;
mjeraKratica = " m";
if (radioButton2.Checked == true)
{
radioButton2.Checked = false;
radioButton1.Checked = true;
}
if (radioButton3.Checked == true)
{
radioButton3.Checked = false;
radioButton1.Checked = true;
}
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
mjera = 1;
mjeraKratica = " cm";
if (radioButton1.Checked == true)
{
radioButton1.Checked = false;
radioButton2.Checked = true;
}
if (radioButton3.Checked == true)
{
radioButton3.Checked = false;
radioButton2.Checked = true;
}
}
private void radioButton3_CheckedChanged(object sender, EventArgs e)
{
mjera = 10;
mjeraKratica = " mm";
if (radioButton2.Checked == true)
{
radioButton2.Checked = false;
radioButton3.Checked = true;
}
if (radioButton1.Checked == true)
{
radioButton1.Checked = false;
radioButton3.Checked = true;
}
}
}
It should be pretty simple, depending on your requirements. For example, you could just use a basic if block in your method.
void CalculateStuff()
{
// Get input. Do stuff.
if (IsInvalid)
{
MessageBox.Show("You did a bad thing.");
return; // exit the method.
}
// now that we know the input is good, do other stuff.
}
Substitute IsInvalid with whatever check condition you want that will return true if the input is not valid.

How to keep a running score?

I am making a mini test and I am not sure how to go about making a running score that will update the current score after the user submits the test. The score can fluctuate by 25 points depending on if the question goes from wrong to right, and vice versa.
public partial class _Default : System.Web.UI.Page
{
private int totalScore = 0;
public void IncrementScore()
{
totalScore += 25;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblHeader.Text = "quiz not taken";
}
else
{
lblHeader.Text = "Score: " + totalScore;
}
}
protected void Submit_Click(object sender, EventArgs e)
{
/***************************************************************************/
if (IsValid)
if (txtAnswer.Text.Equals("primary", StringComparison.InvariantCultureIgnoreCase))
{
lblQuestionResult1.ForeColor = System.Drawing.Color.Green;
lblQuestionResult1.Text = "Correct";
}
else
{
lblQuestionResult1.ForeColor = System.Drawing.Color.Red;
lblQuestionResult1.Text = "Incorrect";
}
/***************************************************************************/
if (ddList.SelectedItem.Text.Equals("M:N"))
{
lblQuestionResult2.ForeColor = System.Drawing.Color.Green;
lblQuestionResult2.Text = "Correct";
}
else
{
lblQuestionResult2.ForeColor = System.Drawing.Color.Red;
lblQuestionResult2.Text = "Incorrect";
}
/***************************************************************************/
if (RadioButton4.Checked == true)
{
lblQuestionResult3.ForeColor = System.Drawing.Color.Green;
lblQuestionResult3.Text = "Correct";
}
else
{
lblQuestionResult3.ForeColor = System.Drawing.Color.Red;
lblQuestionResult3.Text = "Incorrect";
}
/***************************************************************************/
lblQuestionResult4.ForeColor = System.Drawing.Color.Red;
lblQuestionResult4.Text = "Incorrect";
if (Answer2.Checked && Answer3.Checked && !Answer1.Checked && !Answer4.Checked)
{
lblQuestionResult4.ForeColor = System.Drawing.Color.Green;
lblQuestionResult4.Text = "Correct";
}
}
}
The approach of incrementing
private int totalScore = 0;
will not work because you get a new instance of _Default for every HTTP request.
You can keep your running score in Session.
However, I would instead suggest always recalculating the total score when needed by looping through the answers and score associated with each answer as needed. This simplifies the logic if people go back and change an answer (assuming it is permitted to do that).
Modify it to something like see, check syntax, was not using VS
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblHeader.Text = "quiz not taken";
}
else
{
Session["TotalScore"] = ""+totalScore; //Storing it in a session
lblHeader.Text = "Score: " + Session["TotalScore"];
}
}
//increment method
if(Session["TotalScore"]!=null)
{
totalScore += 25;
}
else
{
totalScore=int.Parse(Session["TotalScore"])+25;
}

Windows Phone Preserving Page State not working

I am trying to preserve the page state when i go to another page, but for some reason when i go back to this page, the items are returned to their default state. Why doesn't it work? It seems to follow the tutorials perfectly...
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
State["Title"] = TitleTextBox.Text;
//all of those are RadioButtons - if their is a better way to do it then please comment :)
int i = new int();
if (RB0.IsChecked.Value)
i = 0;
else if (RB1.IsChecked.Value)
i = 1;
else if (RB2.IsChecked.Value)
i = 2;
else if (RB3.IsChecked.Value)
i = 3;
State["CheckedRB"] = i;
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (State.ContainsKey("Title"))
TitleTextBox.Text = State["Title"] as string;
if (State.ContainsKey("CheckedRB"))
{
int i = (int)State["CheckedRB"];
if (i == 0)
RB0.IsChecked = true;
else if (i == 1)
RB1.IsChecked = true;
else if (i == 2)
RB2.IsChecked = true;
else if (i == 3)
RB3.IsChecked = true;
}
}
Edit: I traced the problem by adding breakpoints.
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
State["Title"] = TitleTextBox.Text;
string look0 = WorkOutName.Text;
string look = State["WorkOutName"] as string;
int i = new int();
if (RB0.IsChecked.Value)
i = 0;
else if (RB1.IsChecked.Value)
i = 1;
else if (RB2.IsChecked.Value)
i = 2;
else if (RB3.IsChecked.Value)
i = 3;
State["CheckedRB"] = i; <-------- breakpoint
and here are the results:
(OnNavigatedFrom)
look0 : "Text From TextBox"
look1 : "Text From TextBox"
i : (0, 1, 2, or 3)
and same with OnNavigatedTo:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (State.ContainsKey("Title"))
TitleTextBox.Text = State["Title"] as string; <--breakpoint
if (State.ContainsKey("CheckedRB"))
{
int i = (int)State["CheckedRB"]; <--breakpoint
if (i == 0)
RB0.IsChecked = true;
else if (i == 1)
RB1.IsChecked = true;
else if (i == 2)
RB2.IsChecked = true;
else if (i == 3)
RB3.IsChecked = true;
}
}
and Neither one of them (on OnNavigatedTo) go off.
I tried your code and it seems to work fine. I don't know if this is your case, but remember that if you have the following navigation flow in the app:
Page1 (forward navigation)-> Page2 (back navigation)-> Page1 (forward navigation)-> Page2
If you saved the state in Page2 when first visiting it, that state will NOT be preserved when returning to Page2 again, this is because when doing a back navigation the page is discarded and so is the state dictionary for that page. You can read more about that in the documentation.

how to loop through some ASP.NET labels to set their attributes?

How do I do this in a loop.
protected void ddlTool_SelectedIndexChanged(object sender, EventArgs e)
{
lblTool1.Visible = false;
txtTool1.Visible = false;
lblTool2.Visible = false;
txtTool2.Visible = false;
lblTool3.Visible = false;
txtTool3.Visible = false;
lblTool4.Visible = false;
txtTool4.Visible = false;
lblTool5.Visible = false;
if (ddlTool.SelectedValue == "1")
{
lblTool1.Visible = true;
txtTool1.Visible = true;
}
if (ddlTool.SelectedValue == "2")
{
lblTool1.Visible = true;
txtTool1.Visible = true;
lblTool2.Visible = true;
txtTool2.Visible = true;
}
if (ddlTool.SelectedValue == "3")
{
lblTool1.Visible = true;
txtTool1.Visible = true;
lblTool2.Visible = true;
txtTool2.Visible = true;
lblTool3.Visible = true;
txtTool3.Visible = true;
}
if (ddlTool.SelectedValue == "4")
{
lblTool1.Visible = true;
txtTool1.Visible = true;
lblTool2.Visible = true;
txtTool2.Visible = true;
lblTool3.Visible = true;
txtTool3.Visible = true;
lblTool4.Visible = true;
txtTool4.Visible = true;
}
Instead of having a separate variable for each textbox and label, have a collection of them - whether that's a List<T> or an array or whatever.
Then you can do:
// Potentially use int.TryParse here instead
int visibleLabels = int.Parse(ddlTool.SelectedValue);
for (int i = 0; i < labels.Count; i++)
{
labels[i].Visible = (i < visibleLabels);
textBoxes[i].Visible = (i < visibleLabels);
}
(Alternatively use two loops, one to set some Visible properties to true, and one to set some to false.)
You can access a control by its name using
container.Controls["nameofcontrol"]
So technically, you could use this to lookup your control
(Untested code)
for(int index = 1; index <= Convert.ToInt32(ddlTool.SelectedValue); index++)
{
this.Controls["lblTool" + index.ToString()].Visible = true;
this.Controls["txtTool" + index.ToString()].Visible = true;
}
Use a UserControl for each set of connected controls and then enable/disable the UserControl instead of all the component controls. This is classic, basic modularization of your user interface.
Note that this will still require a little "redundant" code because you're working with an unusual UI paradigm by enabling up-to the ddlTool's selected value of your control. E.g., create your user control that contains a single Label and TextBox. Call it LabeledTextBox or something similar. Then you'd create a collection of your labeled text boxes and enable them up to int.Parse(ddlTool.SelectedValue) - 1.
foreach (Control ctrl in this.Controls)
{
int index = (int)ctrl.Name.Substring(ctrl.Name.Length - 1);
int maxIndex = (int)ddlTool.SelectedValue;
ctrl.Visible = (index <= maxIndex);
}
Here is an example with no error checking, but should match your code functionality.
protected void ddlTool_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedValue = int.Parse(ddlTool.SelectedValue.ToString());
for (int i = 1; i <= 4; ++i)
{
bool state = i <= selectedValue;
this.Controls["lblTool" + i.ToString()].Visible = state;
this.Controls["txtTool" + i.ToString()].Visible = state;
}
}

Categories

Resources