ASP.Net C# Variables not storing on web page - c#

So i have the code..
int var1 = 0;
protected void cmdvar1_Click(object sender, EventArgs e)
{
var1= var1+ 10;
lblvar1.Text = var1.ToString();
}
And when clicking this, its great.. it takes the int, adds 10 to it, then displays it.. however it won't display any more than 10, did some playing around and came to the conclusion, that its not because the label isnt updating, it just simply isnt adding 10 to the previous 10 on the variable. What am i doing wrong? What am I mising? Do i need to store the variable info in a cookie or something?

This is due to the lifecycle of ASP.NET. Storing private fields behind the web page isn't the same as how it works with WinForms. If you want to persist information across post backs you need to store it in some persistent storage i.e. Session/ViewState/Database etc.
private int var1 = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// load var1 from cache
Int32.TryParse((Session["var1"] ?? 0).ToString(), out var1);
}
}
protected void cmdvar1_Click(object sender, EventArgs e)
{
var1 += 10;
Session["var1"] = var1; // cache var1
lblvar1.Text = var1.ToString();
}

So I would strongly suggest looking into a different platform. Perhaps ASP.NET MVC... However you can use something like the following to get arround your problem.
private int MyNum
{
get{ return (int)ViewState["MyNum"] ?? 0; }
set { ViewState["MyNum"] = value; }
}
Then just use MyNum as your integer your incrementing.

Assuming that lblvar1 is a Label control then you can do the following. The reason this will work is because .NET automatically take care of the state of UIControl
protected void cmdvar1_Click(object sender, EventArgs e)
{
var var1 = Convert.ToInt32(lblvar1.Text);
var1= var1+ 10;
lblvar1.Text = var1.ToString();
}

As suggested in the comments, you have to wrap your universe around statelessness before you will get to producing meaningful web applications.
The ASP.NET equivalent to accomplish state-like behavior is to use the Session collection which is available to every web page.
protected void cmdvar1_Click(object sender, EventArgs e)
{
int var1 = (int)Session["yourInteger"];
var1 += 10;
Session["yourInteger"] = var1;
lblvar1.Text = var1.ToString();
}
You are obviously setting an initial value for Session["yourInteger"] somewhere else, just one time.
The problem with Session is that it makes your application potentially buggy and somewhat unscalable. The more you use it, the worse on both accounts.

Use Session body, HTTP is a stateless Protocol, once you postback you loose the current variable value,
Solution:
int var1=0;
protected void cmdvar1_Click(object sender, EventArgs e)
{
if(Session["var1"]!=null)
var1=int.Parse(Session["var1"].ToString());
else
var1=0;
var1= var1+ 10;
lblvar1.Text = var1.ToString();
Session["var1"]=var1;
}

Related

Like/ Dislike button not working properly

I am trying to make a like and a dislike button. The like button works perfectly but when the dislike button is clicked it doesnt do anything and when it is clicked again it removes a like.
What can I do to fix this problem;
I have a like button(iconButton1) a dislike button(iconButton1) and a label(label1).
int i;
int like;
int dislike;
private void iconButton1_Click(object sender, EventArgs e)
{
like = i ++ ;
label1.Text = like.ToString();
}
private void iconButton2_Click(object sender, EventArgs e)
{
dislike = like -- ;
label1.Text = dislike.ToString();
}
It sounds like you're keeping track of the number of times a button is clicked. If this is the case, then you don't need i at all - just variables that represent the "Like" and "Dislike" buttons:
int like;
int dislike;
private void iconButton1_Click(object sender, EventArgs e)
{
// Pre-increment 'like' and display it's value
label1.Text = ++like.ToString();
}
private void iconButton2_Click(object sender, EventArgs e)
{
// Pre-increment 'dislike' and display it's value
label1.Text = ++dislike.ToString();
}
Notice there's a subtle difference between a pre-increment (++variable) and post-increment (variable++). The pre-increment will use the incremented value in the expression, and the post-increment will use the non-incremented value in the expression.
Eric Lippert describes it much better here: What is the difference between i++ and ++i?

Store information using session variable

I'm new to ASP.NET :) and I'd like to understand more about session. Here's a simple example: Every time I click the button it will add one more integer to listInt and I store the list using Session["listInt"].
public partial class TestSession : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["listInt"] == null)
{
Session["listInt"] = new List<Int16>();
}
}
}
protected void AddInt_Click(object sender, EventArgs e)
{
Int16 i = 0;
List<Int16> listInt = (List<Int16>)Session["listInt"];
listInt.Add(i);
Session["listInt"] = listInt;
Response.Write("Hello!");
}
}
Here's the thing I don't understand, if I comment the line Session["listInt"] = listInt;, whenever I click the variable Session["listInt"] still store the value (means still add more integer to the list):
Int16 i = 0;
List<Int16> listInt = (List<Int16>)Session["listInt"];
listInt.Add(i);
//Session["listInt"] = listInt; //No idea why....
Response.Write("Hello!");
Can anyone please tell me how session works in this case? Thanks in advance :)
Your list is a reference type, so when you retrieve it from the server via the session state container you actually get a reference to some object in the server memory. Hence no need to reassign it later.

Why can't I get the value from textbox?

I've just started learning ASP.NET and I'm facing a problem with getting textbox values. I want to do a simple calculator with only 4 basic operations but what happens is that after I click the + sign and click Go, I see that I didn't store the first number at all. Second number is fine though. Here is a sample of my code.
public partial class deafult : System.Web.UI.Page
{
public TextBox output = new TextBox();
public double temp,tempAdd, calc;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnAdd_Click(object sender, EventArgs e)
{
tempAdd = Convert.ToDouble(output.Text);
output.Text = String.Empty;
}
//User enters another number after clicking Add button then clicks Proc
protected void proc_Click(object sender, EventArgs e)
{
temp = Convert.ToDouble(output.Text);
calc = tempAdd + temp;
output.Text = calc.ToString();
}
}
I debugged and tempAdd is always 0 but I get the number in temp. temp variables and calc is defined public.
You essentially have the problem with all of your variables being re-initialized on load of the page. Unlike winforms, web is stateless.
There are ways of persisting state between refreshes, however. The most obvious choice for your application would be to only go to the server once with the both values and what you want to do with them. ie One button click.
However, for personal edification, it may be worth looking up ViewState. This allows you to store values in an array of sorts and retrieve them even after a refresh.
There are also Session and Application level arrays in ASP.NET that work in similar ways.
Every time you call the page (by events) all your properties is initialized.
Try to do all your logic in one event or store your properties in manager / service / db.
In web (Asp.Net) on every postback properties will get cleared, try to use ViewState or Session variables to hold these values. Refer Asp.Net State Management concepts from MS.
Hope this may help you.
Web controls are State less so you should user session sate to hold the first value then do your stuff...
Ex:-
protected void btnAdd_Click(object sender, EventArgs e)
{
Session["tempAdd"] = output.Text;
output.Text = String.Empty;
}
protected void proc_Click(object sender, EventArgs e)
{
temp = Convert.ToDouble(output.Text);
string oldval=Session["tempAdd"] != null ?Session["tempAdd"].ToString() :"";
if(oldval!="")
tempadd=Convert.ToDouble(oldval);
calc = tempAdd + temp;
output.Text = calc.ToString();
}

Trying to change output for a timer in a form in c#

I need to make a form in C# have a timer and have a label that will have be the display of the timer. The label will need to be a generic label at first saying it is a counter, but when the timer starts it needs to display the count. Currently I have the display as a number up down but, it needs to be the control that can tweak the count, which it does. It just can't be the sole counter.
Here is my assignment:
Create a Windows Application. In the main form, create a label named “lTickCount”.
Create a timer named “tPeriodic”, and a numerical control of your own choosing.
Each time the timer “ticks” increment an integer, display the integer value as a string in
lTickCount. Use the numerical control to change the update rate of the timer
interactively.
I think I have done everything correctly except for the bold part. To finish I tried to make a string in both the label and the counter. I know I shouldn't have in both, I just wanted to show you the two things I've tried to help get better feedback:
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Text = "AAAAAAAA AAAAAAAA ########";
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
TickCounter.Text = "The timer has started";
tPeriodic.Enabled = true;
}
else
{
TickCounter.Text = "The timer has ended";
tPeriodic.Enabled = false;
}
}
private void TickCounter_ValueChanged(object sender, EventArgs e)
{
TickCounter.Text = TickCounter.Value.ToString();
}
private void tPeriodic_Tick(object sender, EventArgs e)
{
TickCounter.Value += 1;
}
private void label1_Click(object sender, EventArgs e)
{
TickCounter.Text = TickCounter.Value.ToString();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
Can someone help me figure out what I'm doing wrong and point me in the right way?
If you are going to try to add to a string (A label value) you need to convert it to an Integer first.
A couple ways to do this:
TextCount.Text = (Convert.ToInt32(TextCount.Text) + 1).ToString();
is one way, of course you could still use your += or any other math syntax for basic addition of +1.
You can also use tryParse, and in fact this should probably be used to verify you have an integer in the first place:
int count;
if (int.TryParse(TextCount.Text, out count))
{
count++;
TextCount.Text = count.ToString();
}
int count;
int tmrInterval = 1000; //1 sec
private void tPeriodic_Tick(object sender, EventArgs e)
{
count++;
lTickCount.Text = count.ToString();
}
private void TickCounter_ValueChanged(object sender, EventArgs e)
{
if (TickCounter.Value == 0)
{
return; // or stop the timer
}
tPeriodic.Interval = TickCounter.Value * tmrInterval;
}
tPeriodic.Interval is the time till next tick in milliseconds.
You are updating the timer interval according to tmrInterval and the value of the numeric control. You can change the interval or the formula i wrote to your own.
valter
Ok I found that:
tPeriodic.Interval = 1000 / Convert.ToInt32(TickCounter.Value * TickCounter.Value);
seemed to work in the numericupdown class.
Thanks for the help.

how to avoid re initialization of session value after redirecting to same page

I have intialized some session variables in page load method to zero. Then I am modifying them in button press method. I am using one session variable as a counter but when I am redirecting the page to the same page, the variables are intialized again. Please help me to prevent this re-initialization. I don't want to use static variables.
The scenario is-
protected void Page_Load(object sender, EventArgs e)
{
session["counter"] = 0;
}
protected void Button1_Click(object sender, EventArgs e)
{
int count = (int)session["counter"];
count++;
session["counter"] = count;
response.redirect("same page");
}
Assuming you just want to check for a non set session variable and if so, set it to zero, then you could just do:
protected void Page_Load(object sender, EventArgs e)
{
if(session["counter"] == null) {
session["counter"] = 0;
}
}
There are also a range of client side options you could use, depending on the situation.
Use
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
session["counter"]=0;
}
protected void Button1_Click(object sender, EventArgs e)
{
int count=(int)session["counter"];
count++;
session["counter"]=count;
//remove response.redirect("same page");
}
Your buuton is server side so your page will postback so you do not need to use response.redirect("same page");
If you are indeed redirecting, and not posting back, just check, on page load, if your initial variable has been set? If not, set it. If it is set, ignore setting it.
'set initial value
if session("counter") is nothing then
session("counter") = 0
end if
If you are posting back, you could also use the above, or you could:
If not isPostBack then
session("counter") = 0
end if
You can move that initialisation to a different page. Instead of directly jumping to your "same page" from another part of your application, julp to an "initializer" instead. That page initializes your session variables and immediately redirects to your "same page".
Your "Button_Click" still redirects to "same page", bypassing that initialisation.

Categories

Resources