Click here to Skip to main content
15,884,986 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
I have a a textbox where the user would enter a score. When a button is click that score would be entered in a listbox and the textbox would be cleared.

The problem is that I want to keep a running total. For example if 3 is entered then total should be 3, next when 7 is entered total should be 10.

What I have tried:

int total;
            ViewState["total"] = 0; 
            int num = Convert.ToInt32(txtScore.Text);
            total = total + num;
            Label1.Text = total.ToString();
Posted
Updated 1-Mar-17 2:53am
Comments
Karthik_Mahalingam 1-Mar-17 8:40am    
what is the significance of listbox here ?
Member 9331278 1-Mar-17 8:46am    
As a record, to store a category and the score.
And later transfer all the categories and score to a database.
Karthik_Mahalingam 1-Mar-17 8:48am    
Is listbox related to this issue?
Member 9331278 1-Mar-17 8:52am    
no, the listbox has nothing to do with it
Karthik_Mahalingam 1-Mar-17 8:57am    
OkJust sum up the data and display?

You can do it a bunch of different ways, such as hidden fields above. To do it using ViewState I would do the following.

int total;
int num = Convert.ToInt32(txtScore.Text);
if (ViewState["total"] == null)
{
	total = 0;
}
else
{
	total = (int)ViewState["total"] + num;
}
ViewState["total"] = total;
Label1.Text = total.ToString();
 
Share this answer
 
Comments
Graeme_Grant 1-Mar-17 8:59am    
Yep, it all gets packed into the page.
Member 9331278 1-Mar-17 9:02am    
thank for the response. However there is a slight problem.
the first score is not being added. For example if 3 is entered total= 0, next 4 is added total = 4 then 5 is added total = 9
Graeme_Grant 1-Mar-17 9:07am    
if you set a breakpoint and step through the code, you can see what is happening. Here is the fix:
if (ViewState["total"] == null)
{
	total = num;
}
Please do yourself a big favor and learn how to use the debugger, it will save you hours of work! Basic Debugging with Visual Studio 2010 - YouTube[^]
Member 9331278 1-Mar-17 9:10am    
Thanks it works appreciated very much
jgakenhe 1-Mar-17 9:42am    
Thanks Graeme.
Use a hidden field[^]
 
Share this answer
 
Comments
Member 9331278 1-Mar-17 8:48am    
thanks for you response. Can you be more specific?
Graeme_Grant 1-Mar-17 8:54am    
The link provided has a lot more information with examples of how to use it - did you look at it?

Think of a hidden field as a variable. You can write to it and you can read it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900